Hi there!
I’m currently learning how to write shaders in Unity. I’ve been following some tutorials on how to write a shader that utilizes depth texture in URP, but unfortunately, I’m unable to achieve the same result as in the tutorial for some unknown reasons. It seems that SampleSceneDepth always returns 0, regardless of the position of my test object.
To check this idea, I decided to write a simple shader that would visualize the depth texture. However, for some reason, the color returned by the shader is always black. I have already enabled the DepthTexture checkbox on the URP asset. Here’s the code for my shader. Can anyone please tell me what I did wrong?
Shader "Custom/DepthTextureVisualize"
{
Properties {}
SubShader
{
Tags
{
"RenderType" = "Opaque"
"RenderPipeline" = "UniversalPipeline"
}
Pass
{
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"
struct appdata
{
float4 positionOS : POSITION;
};
struct v2f
{
float4 positionHCS : SV_POSITION;
};
v2f vert(appdata IN)
{
v2f OUT;
OUT.positionHCS = TransformObjectToHClip(IN.positionOS.xyz);
return OUT;
}
float4 frag(v2f IN) : SV_Target
{
float2 UV = IN.positionHCS.xy / _ScaledScreenParams.xy;
float depth = SampleSceneDepth(UV);
return float4(depth, depth, depth, 1.0);
}
ENDHLSL
}
}
}