How to update shader parameters in a shader with stencil (UI.Mask) ?

I’m trying in a run-time update parameters for a shader in a material for an element that is a child element of a UI.Mask.

Problem is that if I include this code in my shader:

        _StencilComp ("Stencil Comparison", Float) = 8
        _Stencil ("Stencil ID", Float) = 0
        _StencilOp ("Stencil Operation", Float) = 0
        _StencilWriteMask ("Stencil Write Mask", Float) = 255
        _StencilReadMask ("Stencil Read Mask", Float) = 255
        _ColorMask ("Color Mask", Float) = 15

and in SubShader section

        Stencil
        {
            Ref [_Stencil]
            Comp [_StencilComp]
            Pass [_StencilOp]
            ReadMask [_StencilReadMask]
            WriteMask [_StencilWriteMask]
        }
        ColorMask [_ColorMask]

My code in C# script (inside Update()):

m_mat.SetColor("_Color", m_color);

is executed only once. All subsequent calls to .SetColor do not update the value.

If I remove stencil code, everything works and color changing every frame, but then mask does not have any effect and a whole image is revealed. It is very similar to Masked UI Element's Shader Not Updating - Unity Engine - Unity Discussions. But I cannot change parameter globally as I have multiple instances of the same material and I need different parameters.

Any ideas how to fix it? I looked and googled everywhere, but could not find any working solution…

Not sure if you ever figured out the issue, but I just spent some time on the same thing and am updating the similar threads I read without an answer.

The Mask object causes a modified material to be returned so it is no longer rendering the base material texture but a “on-the-fly” material. Assuming you are using an Image using setColor on the materialForRendering property of Image will set the correct material if a mask is involved.

4 Likes

Thanks :smile: