Using Depth Textures

It is possible to create Render Textures where each pixel contains a high precision "depth" value (see RenderTextureFormat.Depth). This is mostly used when some effects need scene's depth to be available (for example, soft particles, screen space ambient occlusion, translucency would all need scene's depth).

Pixel values in the depth texture range from 0 to 1 with a nonlinear distribution. Precision is usually 24 or 16 bits, depending on depth buffer used. When reading from depth texture, a high precision value in 0..1 range is returned. If you need to get distance from the camera, or otherwise linear value, you should compute that manually.

Depth textures in Unity are implemented differently on different platforms.

Using depth texture helper macros

Most of the time depth textures are used to render depth from the camera. UnityCG.cginc include file contains some macros to deal with the above complexity in this case:

For example, this shader would render depth of its objects:

Shader "Render Depth" {
SubShader {
    Tags { "RenderType"="Opaque" }
    Pass {
        Fog { Mode Off }
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

struct v2f {
    float4 pos : SV_POSITION;
    float2 depth : TEXCOORD0;

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

half4 frag(v2f i) : COLOR {

Page last updated: 2012-09-04