Make a shader that only renders objects behind another object

My question is very similar to this one:

I need the same effect except that I don’t want to draw objects before the object.

Here you can see the culprit box:

I tried to set the stencil quad’s ‘Zwrite’ set to ‘on’, then the culled object’s ‘ZTest’ to ‘GEqual’.
ZTest is working as excepted, only objects behind the quad are rendered but faces are mixed up.

Here’s what I got:

I’m not used to shaders so I don’t know what to do now. Any hints ?

I was able to answer my own question during moderation.

The trick is to change ‘Pass keep’ with ‘Pass invert’ in the culled object shader.

I don’t think you can achieve it this way. Problem is that in order to render triangles of object in correct order it uses ZTest. But you need inverted ZTest for the trick that you’re doing. I don’t think you’ll be able to combine these two things.

Maybe you can achieve it by using multiple passes and Stencil buffer (Unity - Manual: ShaderLab command: Stencil). It’s allows you to write and read bit-mask per pixel.

Something like this:

  1. Your window object must be rendered first (make sure it’s Queue value in shader is less than in the shader of the cullable object)
  2. Render your cullable objects with multiple passes
  3. In first pass do what you do now and write 1 into Stencil buffer for objects which are rendered
  4. In second pass set ZTest to normal one and check that 1 is written in Stencil buffer

Anyway I’m sure you will have some issues with this, because Unity batches objects with multiple passes in a weird way (at least that was my experience) and I was having problem with this approach, but maybe you can figure something out in this direction.