What is the depth buffer?

In modern game development, a renderer sometimes uses a depth buffer (also called a Z-buffer) to store the distance from the camera a certain pixel was rendered. This buffer can be very useful to have when creating custom shader effect for Unity but is unfortunately not always enabled. Luckily there are a few ways to remedy this.


Use the deferred rendering pipeline.

If you use Unity's deferred rendering pipeline the depth buffer is enabled by default because deferred rendering uses it.

You can set your game to use deferred rending by changing it from Edit->Project Settings -> Graphics. Every tier will have a Rendering Path setting from where you can select Deferred.


Enable it manually for a camera.

Create a new C# script for your game as follows and attach it you your camera.

Note: The editors camera will have it's Depth Buffer enabled if the game camera does.

using UnityEngine;

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class EnableDepthTexture : MonoBehaviour {

 private Camera _camera;

 void Start(){
   _camera = GetComponent<Camera>();
   _camera.DepthTextureMode = DepthTextureMode.Depth;
 }
}


Official documentation

https://docs.unity3d.com/ScriptReference/Camera-depthTextureMode.html


Performance impact

Though not a huge issue, by enabling the depth buffer Unity will allocate a new 8bit back buffer in video memory. If rendering at 1920x1080 this buffer will be about 2 MB. Each frame also needs to render each pixel of this buffer. The GPU overhead for this is not large but at least keep it in mind.