I’m trying to make a shader that will render only the depth of an object so that I can utilize it in an image effect. The shader I’m using is the one from here: http://wiki.unity3d.com/index.php?title=DepthMask
This is what the depth looks like with an opaque shader:
And this is what it looks like with the depth only shader:
As you can see, the depth is not writing at all. These images should both be exactly the same.
I could have a problem with my image effect, but I suspect it is more to do with the depth shader.
Can’t you use _CameraDepthTexture in your image effect? Unity creates this texture when using Deferred Rendering always and in Forward Rendering as soon as you turn on shadows, which means that depth-information is often already available without any extra-steps needed.
I am using _CameraDepthTexture. The problem is that the camera’s depth texture isn’t giving me the correct depth. The shader I’m using is meant to draw an invisible object with depth only, but it is drawing an invisible object without depth.
Somewhat unintuitively that depth mask shader isn’t used when rendering the depth texture. Depth is rendered using either replacement shaders (when rendering depth & normals in forward rendering), or with the shadowcaster shader pass (when rendering depth in forward rendering or shadow maps). Deferred rendering with DX11 will use the real depth and this shader will work unedited.
You can write your own shadercaster pass, or you can use fallback, or usepass to point to a shader that has one. Many of the built in shaders use Fallback "Diffuse" or Fallback "Legacy Shaders/Diffuse" or something similar, but this actually adds a couple more things than just the shadowcaster pass. Unity’s own Vertex Fragment Shader Example page uses UsePass "Legacy Shaders/VertexLit/SHADOWCASTER", but they also have an example of the pass a written out.
However there’s a few problems with doing it this way. As you may have noticed this is called a shadowcaster pass. This means your object will now cast shadows, but this is easily fixed by disabling shadow casting on the object’s renderer.
Another problem is the scene depth is also what is used for shadow receiving with the main directional light. This might be fine if you are also using this to block rendering of everything past it, but if anything does render beyond it that receives shadows those shadows will actually be those cast on the depth mask object. The obvious solution might be to uncheck shadow receiving on the renderer as well, but this will prevent it from rendering in the depth buffer. If this is an issue for you then you cannot use the camera’s _DepthTexture and will have to use a replacement shader setup, like the built in _DepthNormalTexture you can enable on cameras via script, or write some code to render your object’s depth and merge it with the _DepthTexture into a new depth rendertexture and use that.