Can't Get Simple Transparency Shader To Work
Hi everyone, I'm trying to build a shader for transparent sprites, which can adjust the alpha of the sprites using a Range() variable. However, when I try adjusting the alpha of the sprite in my fragment shader it causes a solid background to appear behind the transparent sprite. I included the code for reference.
Shader "TransparentShader"
{
Properties
{
_MainTex("Texture1", 2D) = "white" {}
_Tween("Tween", Range(0,1)) = 0.0
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"RenderType"="Transparent"
}
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert(appdata v) {
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
float _Tween;
float4 frag(v2f i) : SV_TARGET
{
float4 color = tex2D(_MainTex, i.uv);
// WORKS WITH TRANSPARENCY
//return color;
// RENDERS A SOLID SPRITE BACKGROUND??
return float4(color.r, color.g, color.b, 0.5);
}
ENDCG
}
}
}
When returning a float4 with modified alpha. When returning the original texture's color.
Answer by djooryabi · Mar 18, 2019 at 05:44 AM
So I figured it out. I should be multiplying the texture's alpha by my tween value. This makes sense because if I assign the tween value directly to the fragment output color then transparent regions in the texture will get assigned a non-zero alpha and it will look weird like above. By multiplying the alpha value of the texture by the tween value it insures that zero alpha regions stay zero and will scale the alpha of the other regions accordingly.
So basically I just changed this line,
return float4(color.r, color.g, color.b, _Tween * color.a);
Cheers!