Use depth textures:
Depth information can be rendered to a texture, some effects of the production will require scene depth information, at this time depth texture can come in handy.
Depth texture have different implementations on different platforms, and native support is not the same.
Unitycg.cginc defines some of the help macros defined using depth texture:
Unity_transfer_depth (o) calculates the depth value of the eye space and writes the variable O (FLOAT2). Use this function in vertex shader when you need to render to a depth map. On a platform that supports depth texture, the function does nothing, because the value of z buffer is rendered.
Unity_output_depth (i) returns the eye space depth value according to I (FLOAT2). Use this function in fragment shader when you need to render to a depth map. On a platform that originally supported depth texture, the function always returns 0.
Compute_eyedepth (i) calculates the depth value of the eye space. When used in vertex shader, this function is used whenever the value is not rendered to depth texture, but is simply obtained.
Decode_eyedepth (i) obtains the high precision eye space depth from the depth texture I.
Shader"Render Depth"{subshader {Tags {"Rendertype"="Opaque"} Pass {Fog {Mode Off} cgprogram#pragmaVertex vert#pragmaFragment Frag#include"Unitycg.cginc" structv2f {float4 pos:sv_position; FLOAT2 depth:texcoord0; }; v2f Vert (Appdata_base v) {v2f o; O.pos=Mul (UNITY_MATRIX_MVP, V.vertex); Unity_transfer_depth (o.depth); returno; } Half4 Frag (v2f i): COLOR {unity_output_depth (i.depth); } ENDCG} }}
Camera ' s Depth Texture:
Camera can generate a depth texture or depth+normals texture. Can be used to implement some post-processing effects or custom lighting patterns.
Depth texture can come directly from the Depth buffer, or a separate pass based on the shader replacement feature, so you can do it yourself.
Variable: Camera.depthtexturemode
Value:
Depthtexturemode.depth: a screen-sized Depth map.
Depthtexturemode.depthnormals:
The screen-sized (8 Bit/channel) texture contains depth and view space normals information.
noramls are stored in R and G channels, and depth use B and a channels.
[Unitycg.cginc] The Decodedepthnormal (Float4 enc, out float depth, out float3 normal) function can be used to decode pixel and normal values from depth value, returning a depth of 0. 1 of the range.
Using Depth Texture