- Home /
Shader: How to write a shader that respects sorting order first and then depth
I am very new to shaders. I have created a custom editor for MeshRenderer in order for me to edit their sorting order. I want to modify Unity's built-in mobile unlit shader (https://github.com/TwoTailsGames/Unity-Built-in-Shaders/blob/master/DefaultResourcesExtra/Mobile/Mobile-Lightmap-Unlit.shader) to respect the sorting order first and then depth second. If I have objA with sorting order of 100 and objB with sorting order of 0, the objA should be drawn on top of objB, regardless of the depth. However, if they have the same sorting order, then the drawing order should be determined by the depth. However, it seems like the shader is disregarding the sorting order right now.
Any help would be appreciated.
Answer by Bunny83 · Sep 16, 2021 at 01:45 PM
This is not possible with pure shaders since your screen only has a single depth buffer, Either your shader uses the depth buffer or not. What you would need is clearing the depth buffer between your "order" layers. This could be achieved with a custom scriptable renderpipeline where you can introduce as many intermediate steps as you want. Though keep in mind when you clear the depth buffer, things drawn afterwards can not be occluded by geometry rendered before that.
A simple solution if you have just two "layers" is to simply use two cameras and let the second one render only those objects that should appear on top of everything else. The second camera should only clear the depth buffer. This is commonly used for FPS games to render the local weapon model since we don't want the weapon to clip into world geometry. Though if you want to have many layers that behave like that, you would need to implement a custom renderpipeline.
That's all not really trivial. Also keep in mind that opaque geometry behaves very different then transparent geometry. Opaque geometry is usually sorted front to back while transparent geometry needs to be sorted back to front.
Your answer
Follow this Question
Related Questions
Fog not working in my Shader~ 0 Answers
Header for material properties in inspector? 2 Answers
Where do I put this shader code? Getting weird error? 1 Answer
Shader Color 1 Answer
Addition to Standard Shader stopping it from batching? 0 Answers