I have two objects. I use stencilTestFront for closer object and stencilTestBack for further object.
When I move my camera, I see flicker (sometimes the shaders work correctly and sometimes not)
Shader "StencilTestFront"{
Properties{
_MainTex("MainTex",2D)="white"{}
_Color("Color",Color) = (1.0,1.0,1.0,1.0)
}
SubShader{
Pass{
Tags{
"LighMode"="On"
"RenderType"="Opaque"
"Queue"="Geometry+2"
}
Stencil{
Ref 1
Comp Equal
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
uniform sampler2D _MainTex;
uniform fixed4 _Color;
struct VertexInput {
float4 vertrx:POSITION;
float2 uv:TEXCOORD0;
};
struct VertexOutput {
float4 pos:SV_POSITION;
float2 uv:TEXCOORD0;
};
VertexOutput vert(VertexInput v) {
VertexOutput o;
o.pos= mul(UNITY_MATRIX_MVP, v.vertrx);
o.uv = v.uv;
return o;
}
float4 frag(VertexOutput o):COLOR {
return _Color;
}
ENDCG
}
Pass{
Tags{
"LighMode"="On"
"RenderType"="Opaque"
"Queue"="Geometry+2"
}
Stencil{
Ref 1
Comp NotEqual
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
uniform sampler2D _MainTex;
uniform fixed4 _Color;
struct VertexInput {
float4 vertrx:POSITION;
float2 uv:TEXCOORD0;
};
struct VertexOutput {
float4 pos:SV_POSITION;
float2 uv:TEXCOORD0;
};
VertexOutput vert(VertexInput v) {
VertexOutput o;
o.pos= mul(UNITY_MATRIX_MVP, v.vertrx);
o.uv = v.uv;
return o;
}
float4 frag(VertexOutput o):COLOR {
float4 color=tex2D(_MainTex,o.uv);
return color;
}
ENDCG
}
}
}
Shader "StencilTestBack"{
Properties{
_MainTex("MainTex",2D)="white"{}
_Color("Color",Color) = (1.0,1.0,1.0,1.0)
}
SubShader{
Pass{
Tags{
"RenderType"="Opaque"
"Queue"="Geometry+1"
"LighMode"="On"
}
Stencil {
Ref 1
Comp always
Pass replace
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
uniform sampler2D _MainTex;
uniform fixed4 _Color;
struct VertexInput {
float4 vertrx:POSITION;
float2 uv:TEXCOORD0;
};
struct VertexOutput {
float4 pos:SV_POSITION;
float2 uv:TEXCOORD0;
};
VertexOutput vert(VertexInput v) {
VertexOutput o;
o.pos= mul(UNITY_MATRIX_MVP, v.vertrx);
o.uv = v.uv;
return o;
}
float4 frag(VertexOutput o):COLOR {
float4 color=tex2D(_MainTex,o.uv);
color *= _Color;
return color;
}
ENDCG
}
}
}