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.