Unity 3D Shaders for Two Transparent Textures

I like programming. C++ and C# make sense to me. Graphics and shaders, less so. I understand them, I just don’t have much experience with the syntax used in Unity 3D’s shader system.

And so, I was annoyed when I wanted to have a shader that faded between two transparent textures. I assumed that this might be a good way to smooth out 2d animations. But while I could find shaders that would fade between two normal textures, I couldn’t find ANYTHING that supported alpha transparency in those textures.

Anyway, after much experimentation, I made up the shaders myself. They work quite well, too. Sadly, they don’t work well for what I need: the first shader is based on Unity’s transparency shaders, which work great by allowing semi-transparent colors, but this causes errors with rendering order and isn’t good for more complex scenes with a lot of transparent textures. I typically stay away from that and use cutout transparency shaders, which don’t allow semi-transparency, but don’t have the errors I mention. From an animation perspective, the first (transparent) shader looks better, but the second (transparent cutout) is necessary for actual use but doesn’t look as good. I provide both here, hoping it helps some of you out. Maybe I can use it elsewhere…

 

BLEND2TEXTURESALPHA.shader

Shader “Custom/Blend2TexturesAlpha” {

Properties {

_Blend (“Blend”, Range(0,1)) = 0.5
_MainTex (“Tex1”, 2D) = “”
_MainTex2 (“Tex2”, 2D) = “”
}

SubShader {
Tags{ “Queue”=”AlphaTest” “IgnoreProjector”=”True” “RenderType”=”Transparent” }
Pass   {
Blend SrcAlpha OneMinusSrcAlpha
SetTexture[_MainTex]{
Combine texture
}
SetTexture[_MainTex2] {
ConstantColor(0,0,0,[_Blend])
Combine texture Lerp(constant) previous
}
}
}

Fallback “Transparent/VertexLit”

}

BLEND2TEXTURESALPHACUTOUT.shader

Shader “Custom/Blend2TexturesAlphaCutout” {

Properties {
_Cutoff (“Alpha Cutoff”, Range(0,1)) = 0.5
_Cutoff2 (“Alpha Cutoff 2”, Range(0,1)) = 0.5
_Color (“Main Color”, Color) = (1,1,1,1)
_MainTex (“Tex”, 2D) = “”
_MainTex2 (“Tex2”, 2D) = “”
}

SubShader {
Tags{ “Queue”=”AlphaTest” “RenderType”=”TransparentCutout” }
LOD 200

CGPROGRAM
#pragma surface surf Lambert alphatest:_Cutoff
sampler2D _MainTex;
fixed4 _Color;
struct Input {    float2 uv_MainTex;   };
void surf (Input IN, inout SurfaceOutput o) {
fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;    o.Alpha = c.a;
}
ENDCG

CGPROGRAM
#pragma surface surf Lambert alphatest:_Cutoff2
sampler2D _MainTex2;
fixed4 _Color;
struct Input {    float2 uv_MainTex;   };
void surf (Input IN, inout SurfaceOutput o) {
fixed4 c = tex2D(_MainTex2, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;    o.Alpha = c.a;
}
ENDCG

}

Fallback “Transparent/Cutout/VertexLit”
}

 

 

 

 

 

One thought on “Unity 3D Shaders for Two Transparent Textures

Comments are closed.