using UnityEngine; public class ShowCameraDepthTexture : MonoBehaviour { public Material mat; private void Awake() { Camera camera = this.GetComponent<Camera>(); //只要将相机的这个参数设置为Depth就可以在Shader中使用_CameraDepthTexture访问深度贴图了 camera.depthTextureMode = DepthTextureMode.Depth; } private void OnRenderImage(RenderTexture source, RenderTexture destination) { if (mat != null) { Graphics.Blit(source, destination, mat); } else { Graphics.Blit(source, destination); } } }
Shader "Unlit/DepthTexShow" { Properties { _MainTex ("Texture", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float2 uv : TEXCOORD0; float4 vertex : SV_POSITION; }; sampler2D _MainTex; float4 _MainTex_ST; sampler2D _CameraDepthTexture; v2f vert (appdata_img v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = v.texcoord; return o; } fixed4 frag (v2f i) : SV_Target { //SAMPLE_DEPTH_TEXTURE 用来取样深度贴图 float d = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture,i.uv); d = Linear01Depth(d); //转换到线性空间,并且约束在0-1,原本是经过剪裁矩阵的,非线性 return fixed4(d,d,d,1);//可视化 } ENDCG } } }
调节相机Camera的Clipping Planes的Far属性到最远物体可以看见的位置,因为如果差太远的话深度图就会约束到很小值的地方了(黑色)