- Home /
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?
Thanks!
Answer by tanoshimi · Nov 01, 2016 at 10:26 PM
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: https://docs.unity3d.com/Manual/SL-MultipleProgramVariants.html
You can alter and re-compile at runtime, no? Do they not get compiled at runtime, anyway? I've done it before in OpenGL (in C), where I add parts to the shader at runtime.
It's less that I want to have different versions for the shaders, it's more that I want to simply add a few lines to every existing shader currently running under a GameObject. So all their children's shaders will have the following snippet:
Stencil
{
Ref 1
Comp Equal
}
I don't want to add this manually to each of the shaders that they're using, simply because there are so many, and I'd have to go through them to find out what they are.
I'm looking for an answer to the exact same question. Any luck?
As I said previously, you can switch shaders assigned to a material at runtime or enable/disable a keyword that turns on some conditional feature, but you can't arbitrarily insert a line into a shader (just as you can't insert a line into the Update() function of a component).
Your answer
Follow this Question
Related Questions
How to clear the stencil buffer? 1 Answer
Using stencil buffer as form of zwrite? 0 Answers
Problem with transparency and stencil shader 1 Answer
Shader that renders pixel with highest alpha value? 0 Answers
Multi-shader Stencil Buffer not working as expected,Multi-shader Stencil not working as expected 0 Answers