1 Shader "Custom/Opaque" 2 { 3 Properties 4 { 5 [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {} 6 _Color ("Tint", Color) = (1,1,1,1) 7 8 // required for UI.Mask 9 _StencilComp ("Stencil Comparison", Float) = 8 10 _Stencil ("Stencil ID", Float) = 0 11 _StencilOp ("Stencil Operation", Float) = 0 12 _StencilWriteMask ("Stencil Write Mask", Float) = 255 13 _StencilReadMask ("Stencil Read Mask", Float) = 255 14 _ColorMask ("Color Mask", Float) = 15 15 } 16 SubShader 17 { 18 Tags 19 { 20 // ... 21 } 22 23 // required for UI.Mask 24 Stencil 25 { 26 Ref [_Stencil] 27 Comp [_StencilComp] 28 Pass [_StencilOp] 29 ReadMask [_StencilReadMask] 30 WriteMask [_StencilWriteMask] 31 } 32 ColorMask [_ColorMask] 33 34 Pass 35 { 36 // ... 37 } 38 } 39 }
9~14行以及24~32行是解决的方案
完整:
Shader "UI/Default Gray" { Properties { [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {} _Color("Tint", Color) = (1,1,1,1) _MyColor("MyColor", Color) = (1,1,1,1) // required for UI.Mask _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 } SubShader { Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" "PreviewType" = "Plane" "CanUseSpriteAtlas" = "True" } // 源rgba*源a + 背景rgba*(1-源A值) Blend SrcAlpha OneMinusSrcAlpha Cull Off ZWrite Off ZTest Always Pass { Stencil { Ref[_Stencil] Comp[_StencilComp] Pass[_StencilOp] ReadMask[_StencilReadMask] WriteMask[_StencilWriteMask] } ColorMask[_ColorMask] CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct appdata_t { float4 vertex : POSITION; float4 color : COLOR; float2 texcoord : TEXCOORD0; }; struct v2f { float4 vertex : SV_POSITION; fixed4 color : COLOR; half2 texcoord : TEXCOORD0; }; sampler2D _MainTex; fixed4 _Color; fixed4 _MyColor; v2f vert(appdata_t IN) { v2f OUT; OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex); OUT.texcoord = IN.texcoord; #ifdef UNITY_HALF_TEXEL_OFFSET OUT.vertex.xy -= (_ScreenParams.zw - 1.0); #endif OUT.color = IN.color * _Color; return OUT; } fixed4 frag(v2f IN) : SV_Target { half4 color = tex2D(_MainTex, IN.texcoord) * IN.color; float grey = dot(color.rgb, fixed3(0.22, 0.707, 0.071)); return half4(grey*_MyColor.r,grey*_MyColor.g,grey*_MyColor.b,color.a); } ENDCG } } }