Fadi Obaji
Fadi Obaji

Reputation: 1494

Unity: Custom shader not obeying alpha (transparency)

This is a custom shader in Unity, it is a 3-colored gradient shader:

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "CustomShaders/ThreeColorsGradientShader" {
     Properties {
         [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
         _ColorTop ("Top Color", Color) = (1,1,1,1)
         _ColorMid ("Mid Color", Color) = (1,1,1,1)
         _ColorBot ("Bot Color", Color) = (1,1,1,1)
         _Middle ("Middle", Range(0.001, 0.999)) = 1

     }

     SubShader {
         Tags {"Queue"="Transparent"  "IgnoreProjector"="True"  "RenderType"="Transparent"}
         LOD 200

         ZWrite Off

         Pass {
         CGPROGRAM
         #pragma vertex vert  
         #pragma fragment frag
         #include "UnityCG.cginc"

         fixed4 _ColorTop;
         fixed4 _ColorMid;
         fixed4 _ColorBot;
         float  _Middle;

         struct v2f {
             float4 pos : SV_POSITION;
             float4 texcoord : TEXCOORD0;
         };

         v2f vert (appdata_full v) {
             v2f o;
             o.pos = UnityObjectToClipPos (v.vertex);
             o.texcoord = v.texcoord;
             return o;
         }

         fixed4 frag (v2f i) : COLOR {
             fixed4 c = lerp(_ColorBot, _ColorMid, i.texcoord.y / _Middle) * step(i.texcoord.y, _Middle);
             c += lerp(_ColorMid, _ColorTop, (i.texcoord.y - _Middle) / (1 - _Middle)) * (1 - step(i.texcoord.y, _Middle));
             //c.a = 1;
             return c;
         }
         ENDCG
         }
     }
 }

After assigning it to a material and used a material on a UIButton, it works as expected, but if i want to change the color alpha of the material (ie. make it transparent), it does NOT respond to those changes.

What's missing in the code?

Upvotes: 1

Views: 3652

Answers (1)

vasmos
vasmos

Reputation: 2586

Edit tested copy this blurb remove ZWrite Off:

SubShader
{
     Tags {"Queue" = "Transparent" "RenderType" = "Transparent"}
     LOD 100
     Blend SrcAlpha OneMinusSrcAlpha

    Pass
    {

enter image description here

Edit to apply to a ui button, uncheck image from your button component, remove sprite, set alpha of color to 0. Add a plane as a child to your button object, size the plane to how you want,apply the shader to the plane.

Upvotes: 1

Related Questions