The 3D Text asset built into Unity renders always on top, regardless of z depth. This helps to avoid z-fighting issues, if your text is coplanar to other geometry in the scene, but often not what you want. I have labels in my scene which I DO want to be hidden by geometry in front. Unfortunately, there is no simple switch to turn on depth testing – even though users have been struggling with this for years, as far as I can tell.
The solution requires a modified font shader, and to be able to use that, you also need to have a font texture in your project. I had to retrieve all the bits and pieces of information from various places, so I though it might be a good idea to list all the steps together. Here we go:
- Download the Unity built-in shader archive from https://unity3d.com/get-unity/download/archive.
- Extract the .zip (at the time of writing: builtin_shaders-5.4.1f1.zip) into some arbitrary folder.
- Import DefaultResources/Font.shader into your project.
- Rename it, e.g. to ZFont.shader.
- Edit the shader source, and change “ZTest Always” to “ZTest LEqual”. Also change the name, e.g. to “GUI/ZText Shader”.
- Create a new material, and link it to your new shader.
- Import a font into the project. This is as easy as dragging a .ttf into the project window. I used OpenSansRegular.ttf from a sample project.
- Show your material in the inspector.
- Unfold the font entry in the project window. You will see a “Font Texture” entry. Drag that into the “Font Texture” area of the material displayed in the inspector.
- In the Text Mesh where you want to use the new shader, change the Mesh Renderer material to your new material. Change the Text Mesh font to your imported font.
And you’re done!