Search Unity

  1. The 2022.1 beta is now available for testing. To find out what's new, have a look at our 2022.1 beta blog post.
    Dismiss Notice

How to read the depth buffer (on CPU)?

Discussion in 'Universal Render Pipeline' started by DennisWardAltair, Jul 10, 2020.

  1. DennisWardAltair

    DennisWardAltair

    Joined:
    Apr 4, 2019
    Posts:
    27
    I'm trying to access the depth buffer on the CPU and haven't had any luck. All I'm getting is grey. The code below is a snippet of what I'm doing, and any help is appreciated:

    Code (CSharp):
    1. RenderTexture colorRT = new RenderTexture(Screen.width, Screen.height, 0, RenderTextureFormat.Default);
    2. RenderTexture depthRT = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.Depth);
    3. Texture2D depthtex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
    4.  
    5. _camera.depthTextureMode = DepthTextureMode.Depth;
    6. _camera.targetTexture = depthRT;
    7. _camera.SetTargetBuffers(colorRT.colorBuffer, depthRT.depthBuffer);
    8. _camera.Render();
    9. _camera.targetTexture = null;
    10. _camera.depthTextureMode = DepthTextureMode.None;
    11.  
    12. RenderTexture.active = depthRT;
    13. depthtex.ReadPixels(new Rect(0, 0, depthRT.width, depthRT.height), 0, 0, false);
    14. depthtex.Apply();
    15. RenderTexture.active = null;
    16.  
    17. System.IO.File.WriteAllBytes("c:/Temp/depthcapture.png", depthtex.EncodeToPNG());
    18.  
    19. Destroy(colorRT);
    20. Destroy(depthRT);
    21. Destroy(depthtex);
     
    KirillKuzyk likes this.
unityunity