Unity3D Chroma Key Shader

I thought that finding a shader that makes an area of a texture of a certain colour transparent would be easy. It turns out that finding an efficient and free chroma key shader required a little bit more digging.

The best implementation I found was on a blog called Pilcrow Pipe, but it was written in OpenGL shader language, not Unity3D’s ShaderLab language which is more universal and allows you to change parameters such as key colour and tolerance through the Unity GUI. So without further ado, here is the ShaderLab port of the chroma key shader.

// Adapted from http://pilcrowpipe.blogspot.jp/2013/03/chromakeyingtransparentbackground.html

Shader Custom/ChromaKey {

    Properties {
        _MainTex (Base (RGB)2D) = white {}
        _thresh (ThresholdRange (016)) = 0.8
        _slope (SlopeRange (01)) = 0.2
        _keyingColor (Key ColourColor) = (1,1,1,1)
    }
    
    SubShader {
        Tags {Queue=Transparent IgnoreProjector=True RenderType=Transparent}
        LOD 100
        
        Lighting Off
        ZWrite Off
        AlphaTest Off
        Blend SrcAlpha OneMinusSrcAlpha 
        
        Pass {
            CGPROGRAM
                #pragma vertex vert_img
                #pragma fragment frag
                #pragma fragmentoption ARB_precision_hint_fastest

                sampler2D _MainTex;
                float3 _keyingColor;
                float _thresh// 0.8
                float _slope// 0.2

                #include “UnityCG.cginc

                float4 frag(v2f_img i) : COLOR {
                    float3 input_color = tex2D(_MainTexi.uv).rgb;
                    float d = abs(length(abs(_keyingColor.rgb – input_color.rgb)));
                    float edge0 = _thresh * (1.0 – _slope);
                    float alpha = smoothstep(edge0_threshd);
                    return float4(input_coloralpha);
                }
            ENDCG
        }
    } 
    
    FallBack Unlit
}

I hope that somebody finds this useful.

Again, all credit for the logic behind the shader goes to this blog post.