How can I make my own shader include file (.cginc or .glslinc)?

I am wondering how I can create my own shader include file (.cginc or .glslinc), I want to reuse my shader code in many different shaders, and a personalized include file could help me in this regard.

  • Should I write anything special in the file except from the structs/functions/variables I want to include in my shaders?
  • Where should I place it in order for Unity to see it?
  • What should I write in the shader in order for it to pick it up?

This is what I found out:

  • Should I write anything special in the file except from the structs/functions/variables I want to include in my shaders?

Generally you probably want to put include guards (#ifndef) in your file, else it might not work in more than one file, which sort of beats the purpose.

  • Where should I place it in order for Unity to see it?
  • What should I write in the shader in order for it to pick it up?

You can place it anywhere in your Assets folder. Accesing it from the shader can the be done by writing either of the two lines of code below:

#include "Assets/path/to/your/shader.cginc"
#include "Assets/path/to/your/shader.glslinc"

The content of the "included" file is just pasted into the original file. So you can write pretty much anything in there, as long as it's still meaningful when pasted into original shaders.

Where to put it: best probably is next to the shaders (in the same folder). If it's in a different folder, use relative path to include it.