How to write a Unity Shader that respects sorting layers?

f.b. picture f.b. · Oct 24, 2015 · Viewed 9k times · Source

I want to sort my Sprites using Unitys sorting Layers. I attached a custom Shader to one of my Sprites. Sadly the Sprite with this shader always draws behind the other Sprites disrespecting the sorting layer.

How to implement sorting layer respect in my Shader?

That's the shader in question: Thanks in advance

Properties {
    _Color ("Color", Color) = (1,1,1,1)
    _MainTex ("Main Tex (RGBA)", 2D) = "white" {}
    _Progress ("Progress", Range(0.0,1.0)) = 0.0
}

SubShader {

    Pass {

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

uniform sampler2D _MainTex;
uniform float4 _Color;
uniform float _Progress;

struct v2f {
    float4 pos : POSITION;
    float2 uv : TEXCOORD0;
};

v2f vert (appdata_base v)
{
    v2f o;
    o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
    o.uv = TRANSFORM_UV(0);

    return o;
}

half4 frag( v2f i ) : COLOR
{
    half4 color = tex2D( _MainTex, i.uv);
    float a = color.a;
    if(i.uv.y < _Progress){
    color = _Color;
    } 
    color.a = a;
    return color;
}

ENDCG

    }
}

}

I know that i need to set some tags like this, but i can't find a proper reference and trial and error lead to nothing:

Tags { "Queue"="Overlay+1" }
ZTest Off
Blend SrcAlpha OneMinusSrcAlpha
Lighting Off
ZWrite On

Answer

The HamsteR picture The HamsteR · Oct 27, 2015

You were on the right track. Here's what you need to add for a proper sprite shader:

  1. If your game is purely 2D you need to disable ZTest so it wouldn't mess with your layer order.
  2. Specify which kind of blending you're going to use.
  3. Tag that your shader is going to the transparency que.

    SubShader{
        Tags{"Queue" = "Transparent"}
        Pass{
            ZTest Off
            Blend SrcAlpha OneMinusSrcAlpha
            //your CGPROGRAM here
        }
    }
    

This tutorial has a great chapter about transparency which is a huge deal when writing a sprite shader.