Customizable Navigation Bar

Friday, December 6, 2013

Masking In Unity

While working on a GUI system for Unity, one of the issues I came across was how to mask objects on the screen. Unity didn't have a default way of handling this, so after looking around I came across something called a "Depth Mask" shader.

Basically this depth mask works by just hiding everything behind it, so while it works great, there are still a few small issues with it. By hiding everything behind it, you need to fiddle around with render queues or different camera set ups if you only want it to use it on certain objects.

The shader for the depth mask is really really simple:

Shader "Depth Mask" {
    SubShader {
//This Queue call tells the graphics card that this should be drawn before any of the geometry. This is what give the shader its ability. It gets drawn before anything else and any thing drawn behind it gets clipped
        Tags {"Queue" = "Geometry-10" }    
        Lighting Off
        ZTest LEqual
        ZWrite On
        ColorMask 0
        Pass {}

The easiest way to stop objects from being masked by the shader is to manipulate the render queue of the material. If you set the render queue to a lower value than the depth mask, it will show up as if the mask wasn't there at all. This allows you to have full control over which objects are masked and which aren't.

Here is an example of the depth mask at work. You can see the two construction workers getting clipped away by this depth mask shader. The construction worker in the back has a special shader that has a lower render queue than the depth mask, so it is completely unaffected by it.

Hopefully you guys found this tutorial useful. If you want to fiddle around with the project viewed above you can find it here: