Depth shaders always appear black
Asked Answered
K

2

0

I can’t view the depth of objects no matter what I try, they just appear black.

I’ve been grabbing code from forums to access depth data, both via camera render targets and material shaders, including this code directly from the manual

Shader "Render Depth 1" {
SubShader{
Tags { "RenderType" = "Opaque" }
Pass {
	CGPROGRAM
  
	#pragma vertex vert
	#pragma fragment frag
	#include "UnityCG.cginc"
  
	struct v2f {
		float4 pos : SV_POSITION;
		float2 depth : TEXCOORD0;
	};
  
	v2f vert(appdata_base v) {
		v2f o;
		o.pos = UnityObjectToClipPos(v.vertex);
		UNITY_TRANSFER_DEPTH(o.depth);
		return o;
	}
  
	half4 frag(v2f i) : SV_Target {
		//UNITY_OUTPUT_DEPTH(i.depth)*10000000;
		half d = i.depth.x / i.depth.y;
		return half4(d * 10, d * 10, d * 10, 1);
	}
	ENDCG
}
}
}

It’s always just black, even messing with camera render path settings, or mainCamera.depthTextureMode = DepthTextureMode.Depth;, or multiplying in case the values are just dark.

How do I get the depth in a material?

Knox answered 13/12, 2023 at 9:46 Comment(0)
O
0

I don’t know if you’re still having this issue but for anyone who comes here some time after, I’ve found this tutorial to be pretty useful, especially by adding this script to the camera :

private void Start(){
    Camera cam = GetComponent<Camera>();
    cam.depthTextureMode = cam.depthTextureMode | DepthTextureMode.Depth;
}
Owner answered 16/10, 2020 at 19:47 Comment(0)
G
0

What Kaldrin proposed wasn’t enough in my case.

The shader where I was using the _CameraDepthTexture actually needed a shadowcaster pass. This shadowcaster pass was filling the _CameraDepthTexture with correct values, and then I could use it. The simplest way to do so is to add FallBack "Legacy Shaders/VertexLit" right before the last } into the shader which uses _CameraDepthTexture.

Taken from here, an answer by Bgolus: https://forum.unity.com/threads/why-isnt-an-object-with-my-custom-material-applied-drawn-on-camera-depth-texture.1390741/#post-8835097

Gulledge answered 13/12, 2023 at 9:33 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.