Depth Buffer and RenderTextures

So you create a RenderTexture with a depth format. Then you create a typical RenderTexture.

Then you set your camera target buffers to the render texture you just created and render.

RenderTexture depthTexture = new RenderTexture(1024,1024, 24, RenderTextureFormat.Depth);
RenderTexture renderTexture = new RenderTexture(1024,1024, 0);

camera1.depthTextureMode = DepthTextureMode.Depth;

camera1.SetTargetBuffers(renderTexture.colorBuffer, depthTexture.depthBuffer);

camera.Render()

My understanding is that “depthTexture” now holds the camera1’s depth at the time rendering.

How do you go about accessing the depth data in depthTexture inside of a fragment shader?

I have seen the somewhat documented examples of accessing _CameraDepthTexture and _LastCameraDepthTexture, but that is the depth from the current and last frames rendered by any camera, not the depth information in “depthTexture”.

I have also seen examples of outputting the camera’s depth in one of the color channels of a RenderTexture using a replacement shader, but this would mean two rendering operations, one for depth to a separate RenderTexture and one for color the other RenderTexture. With this method you would pass the RenderTexture with the depth information to the fragment shader and use a standard sampler2D to access the depth information like you would a color. However you would now have to do two renders instead of one which is wasteful.

Bump.

I will replace this bump with the best assessment of what I can dig up soon if nobody knows anything about my initial question (so the next guy can who is googling this problem can get a reasonable answer).

This is actually quite trivial, simply call SetTexture() on the material you’re using to manually pass the depth texture:

material.SetTexture("_DepthTex", depthTexture);

To sample the texture inside of the surface shader do:

float depthValue = tex2Dproj(_DepthTex, UNITY_PROJ_COORD(IN.screenPos)).r;
1 Like

Do the values have a unit? Is it for example depending on the camera settings to get meter?