I
I
i__egor2022-04-10 10:24:02
Unity
i__egor, 2022-04-10 10:24:02

How to create depth texture in unity?

I want to generate a depth texture in a compute shader. How can I do that? here from c#:

Camera camera = CameraManager.cam;
                resultTexture = new RenderTexture(1024, 768, 32)
                {
                    enableRandomWrite = true
                };
                resultTexture.Create();

                debugImage.texture = resultTexture;

                kernelIndex = shader.FindKernel("CSMain");
                shader.SetTexture(kernelIndex, "Result", resultTexture);
                shader.SetTextureFromGlobal(kernelIndex, "_DepthTexture", "_CameraDepthTexture");
                
                shader.Dispatch(kernelIndex, camera.pixelWidth / 8, camera.pixelHeight / 8, 1);

here is the shader:
#pragma kernel CSMain

RWTexture2D<float4> Result;
Texture2D<float4> _DepthTexture;

[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
  float depth = _DepthTexture[id.xy].r;
        Result[id.xy] = float4(depth, 0, 0, 0);
}

gives an error: "Compute shader (TestCompute): Property (_DepthTexture) at kernel index (0) has mismatching texture dimension (expected 2, got 5)"
if you write Result[id.xy] = float4(0, 0, 0, 0);for example, then everything is fine

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question