How to make shader working right in UGUI mask?

Environment: Unity 4.6.0p1 UGUI

Raw image:

Within mask:

And I have wrote a grayscale shader:

Shader "UI/GrayColor"
{
    Properties
    {
        _MainTex ("Sprite Texture", 2D) = "white" {}
        _GrayScale ("GrayScale", Range(0,1)) = 1
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }
       
        Cull Off
        Lighting Off
        ZWrite Off
        ZTest [unity_GUIZTestMode]
        Fog { Mode Off }
        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"
           
            struct appdata_t
            {
                float4 vertex   : POSITION;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                half2 texcoord  : TEXCOORD0;
            };
           
            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                OUT.texcoord = IN.texcoord;
                return OUT;
            }
           
            sampler2D _MainTex;
            fixed _GrayScale;

            fixed4 frag(v2f IN) : SV_Target
            {
                half4 c = tex2D(_MainTex, IN.texcoord);
                fixed grayscale = Luminance(c.rgb);
                c.rgb = grayscale.xxx * _GrayScale;
                return c;
            }
            ENDCG
        }
    }
}

Make a grayscale material for Image:

Although grayscale image came out, but mask is broken. How can I fix this bug? Thank you.

I have a similar situation with a Mask object that has a image as child.
The image has a custom shader which causes it to ignore the Mask, im sure theres something simple to fix it but cant find it.
If anyone has an idea, please help!

Download the Unity built-in shaders and take a look at ā€œDefaultResourcesExtra/UI/UI-Default.shaderā€ for example. It’s using Stencil, which is missing in your shader (along with a few other things). Stencil is probably used for masking in this context.

        Stencil
        {
            Ref [_Stencil]
            Comp [_StencilComp]
            Pass [_StencilOp]
            ReadMask [_StencilReadMask]
            WriteMask [_StencilWriteMask]
        }
1 Like

I have a question too!Affer adding ā€œStencil {…}ā€ I can’t adjust the UI image by shader when game running!