- Home /
Why does the shader make some transparent pixels non-transparent?
I am trying to write my first shader. I have taken the default image shader and commented out the line that inverts the colors, so it should spit out exactly the same texture as the one that went in. However, this is what the grass looks like with the default unlit shader:
And here is what it looks like with the no-op shader:
Why are some of the pixels which used to be transparent becoming solid green and brown?
Shader "Hidden/ImageEffectShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
//o.vertex = v.vertex;
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
// just invert the colors
//col.rgb = 1 - col.rgb;
return col;
}
ENDCG
}
}
}
Answer by Eno-Khaon · Jun 28, 2020 at 05:49 AM
When you don't set the timing in the Rendering Queue yourself, the shader will default to rendering the objects during the Geometry phase, where transparency will not be supported.
To adjust this within the shader, you'll want to add something like this line:
Tags { "Queue" = "Transparent" }
For more information and available options, take a look at SubShader Tags.
Thanks! But it still looks the same, so I guess there must be more to it...
Ah, yep. There is. I forgot a detail left out there. You also need to set the right Blending $$anonymous$$ode for the shader.
The default Blending $$anonymous$$ode results in the new pixel color being drawn over the existing pixel, without respecting the alpha channel:
Blend One One // Additive
The simple and common blending mode to accommodate transparency is to use [alpha] percentage of the new pixel, blending with [1-alpha] percentage of the new pixel using the existing pixel's color.
Blend SrcAlpha One$$anonymous$$inusSrcAlpha // Traditional transparency