- Home /
How do Image shaders interact with UI Canvas draw order?
Problem
I have a simple 2D lighting setup using two custom shaders (one for lights, one for sprites) attached to Image components in a UI Canvas (introduced in Unity 4.6). When the Canvas is in Render Mode 'Screen Space - Overlay' everything works as intended. However, in Render Mode 'Screen Space - Camera', my light is being drawn behind everything.
Can somebody help me fix my shaders (and/or my camera setup?) so that the light is drawn on top of the background in 'Screen Space - Camera' mode? Please see the reference section below for shader source code!
Example
RENDER MODE OVERLAY -- WORKING AS INTENDED
RENDER MODE CAMERA -- SOME KIND OF DEPTH ISSUE -- NO LIGHTING:
Reference: Sprites, Shaders, and Camera
LIGHT SOURCE:
Shader "UI Lights/Light"
{
Properties
{
_MainTex ("Light Texture", 2D) = "white" {}
_LightColor ("Light Color", Color) = (1.0, 1.0, 1.0, 1.0)
_LightIntensity ("Light Intensity", Range(0.0, 2.0)) = 1.0
}
SubShader
{
Pass
{
Blend DstColor One, Zero One
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
//user defined variables
uniform sampler2D _MainTex;
uniform float4 _LightColor;
uniform float _LightIntensity;
//in/out structs
struct vertexInput
{
float4 vertex : POSITION;
float2 uv_MainTex : TEXCOORD0;
};
struct vertexOutput
{
float4 vertex : POSITION;
float2 uv_MainTex : TEXCOORD0;
};
//vertex
vertexOutput vert(vertexInput v)
{
vertexOutput o;
o.uv_MainTex = v.uv_MainTex;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
return o;
}
//fragment
float4 frag(vertexOutput i) : COLOR
{
float4 lightValue = tex2D(_MainTex, i.uv_MainTex);
return _LightIntensity * _LightColor * lightValue;
}
ENDCG
}
}
}
BACKGROUND:
Shader "UI Lights/Lit"
{
Properties
{
_MainTex ("Sprite Texture", 2D) = "white" {}
}
SubShader
{
Cull Off
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
//user defined variables
uniform sampler2D _MainTex;
//in/out structs
struct vertexInput
{
float4 vertex : POSITION;
float2 uv_MainTex : TEXCOORD0;
};
struct vertexOutput
{
float4 vertex : POSITION;
float2 uv_MainTex : TEXCOORD0;
};
//vertex
vertexOutput vert(vertexInput v)
{
vertexOutput o;
o.uv_MainTex = v.uv_MainTex;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
return o;
}
//fragment
float4 frag(vertexOutput i) : COLOR
{
float4 col = tex2D(_MainTex, i.uv_MainTex);
return float4(col.rgb / 2.0, col.a);
}
ENDCG
}
}
}
CAMERA:
Comment