First of all: I’m well aware of Z-fighting issues but what I’m observing here looks like an error in my code as it even occurs in relatively close distances. The main issue is that I’m using a lot of undocumented functions and it’s very hard to find anything useful on Google.
The shader I’m testing with just reads the value from the depth buffer, compares it to the fragment depth and outputs the difference. The test scene is just one cube and one plane, the cube writes to the depth buffer and the plane cuts the cube diagonally and has the following shader attached to it:
Shader "Custom/DepthTest"
{
SubShader
{
Tags
{
"Queue"="Geometry"
"RenderType"="Opaque"
}
Fog
{
Mode Off
}
Pass
{
Cull Back
ZWrite Off
ZTest Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _CameraDepthTexture;
inline float ZBufferRead(float4 projpos)
{
return tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(projpos)).r;
}
struct v2f {
float4 pos : POSITION;
float4 projpos : TEXCOORD0;
};
v2f vert(appdata_base v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.projpos = ComputeScreenPos(o.pos);
return o;
}
fixed4 frag(v2f i) : COLOR {
float zvalue = ZBufferRead(i.projpos); // Z-Buffer value
float zdepth = LinearEyeDepth(zvalue); // Z-Buffer depth
float fdepth = i.projpos.z; // Fragment depth
float depth_delta = fdepth - zdepth;
return float4(depth_delta, depth_delta, depth_delta, 1);
}
ENDCG
}
}
Fallback "None"
}
In case you want to test it on your machine, remember to enable the depth texture of your scene and editor cameras, for example by attaching this script to the scene camera:
using UnityEngine;
[ExecuteInEditMode]
public class EnableDepth : MonoBehaviour
{
void OnPreCull()
{
if (camera != null) camera.depthTextureMode = DepthTextureMode.Depth;
}
void Update()
{
if (Camera.current != null) Camera.current.depthTextureMode = DepthTextureMode.Depth;
}
}
The result looks as follows:
(right click → open in new tab to see all details)
I got the idea to play around with this from this blog post and the shaders he posted seem to suffer from the same issue. The threads I found on Google did pretty much the same thing (tex2dproj + linearization) but I couldn’t find anything describing my issue.

