Add to existing shader at runtime

I’d like to add a small snippet that simply references the stencil buffer. I’m trying to mask a volume, so I used the stencil buffer with a normal shader. Unfortunately, the model I’m working on has things in it that doesn’t just use the standard shader, so when I replace them all with the new one, they break.

I tried adding the separate shader as another material, but it just didn’t work.

So now, I’d like to add that little snippet into the existing shaders. Any way of doing this, or is there a better way?


Shaders must be compiled - you can’t alter them at runtime. You can however make multiple shader variants with conditional features activated via #pragma shader_feature: Unity - Manual: Declaring and using shader keywords in HLSL