Search Unity

How To Get Depth Map as Texture2D?

Discussion in 'General Graphics' started by tiancaiwrk, Sep 13, 2018.

  1. tiancaiwrk

    tiancaiwrk

    Joined:
    Nov 23, 2017
    Posts:
    35
    hi, here I have a problem with get Camera's depth texture, after a hole day google it, nothing I got..
    I want to get depth map from a camera and get it to Texture2D,
    here is my code;
    Code (CSharp):
    1.  
    2.         public Camera cam;
    3.         public RenderTexture targetColorBuffer;
    4.         public RenderTexture targetDepthBuffer;
    5.         public Texture2D tex2D;
    6.  
    7.  
    8.         [Button(ButtonSizes.Large)] // button shows in inspector
    9.         public void DepthMap()
    10.         {
    11.             cam.depthTextureMode = DepthTextureMode.Depth;
    12.             cam.clearFlags = CameraClearFlags.Skybox;
    13.  
    14.             if(targetColorBuffer == false)
    15.             {
    16.                 targetColorBuffer = new RenderTexture(1024, 1024, 32, RenderTextureFormat.ARGB32);
    17.                 targetColorBuffer.Create();
    18.             }
    19.             if(targetDepthBuffer == false)
    20.             {
    21.                 targetDepthBuffer = new RenderTexture(1024, 1024, 32, RenderTextureFormat.Depth);
    22.                 targetDepthBuffer.Create();
    23.             }
    24.  
    25.             cam.SetTargetBuffers(targetColorBuffer.colorBuffer, targetDepthBuffer.depthBuffer);
    26.             cam.Render();
    27.             cam.targetTexture = null;
    28.  
    29.             if(tex2D == false)
    30.             {
    31.                 tex2D = new Texture2D(1024, 1024, TextureFormat.RFloat, false);
    32.             }
    33.  
    34.             tex2D.LoadRawTextureData(targetDepthBuffer.depthBuffer.GetNativeRenderBufferPtr(), 1024 * 1024 * 4);
    35.             tex2D.Apply();
    36.         }
    it dose some times crash the editor, some times not. and the [targetColorBuffer] and [targetDepthBuffer] shows correct in inspector, but the tex2D is looks like Gaussian noise map....

    any ideas about it? thanks for any reply
     
  2. tiancaiwrk

    tiancaiwrk

    Joined:
    Nov 23, 2017
    Posts:
    35
    runs on Unity2017.3 Editor Mode