How to Render an Background on Top

hi

For filtrate issues I want to render the background AFTER all other objects.
My idea is to render the bg texture only to places where no other pixel was drawn already.
The idea is ok, but the shader is not working for me.
I have a simple shader with zwrite off. But how to make a ztest like only if z is unlimited ?

Also how can I enforce to render the background after all other objects?

Greetings

Nice issue,

I will present an alternative option before answering your question.
The first thing you do need for both, is layers. You can use a layer and set different object in a layer. For your background, you could create a background layer.

Option 1 (Pro only)

Use a post-effect with RenderTexture to check in your texture if alpha is still 0 on that pixel. If so, it is certain that there was no object there. You can draw a pixel from your background there.

Option 2

Create 2 cameras. One main camera, one second camera that only renders your object (by using the layers). Make sure that the second camera doesn't clear ANYTHING. Also, the depth-buffer needs to stay full.

The background-camera needs a different depth. This will control the rendering order. Now, we can adjust the ZTest in the shader for the background object.

I haven’t tested this, but in theory it looks fine to me.


I was thinking of more options, but I lost them while writing. Option 2 is probably implementable in the easiest way, because you don’t have to write a post-effect. Camera depth is very important to control your render path. If I can think of more, I’ll update this answer.

Are you sure Unity doesn’t already draw Opaque geometry objects front-to-back (the transparent ones in the reverse order)? Seems a pretty obvious optimisation.