Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Stencil Buffer and Depth

Discussion in 'Shaders' started by Lucospade, Aug 10, 2023.

  1. Lucospade


    Aug 23, 2014
    I am trying to set up a system that allows me to see throw blocking objects whenever they obscure the player. I have tried a few ways of doing this each with their own pitfalls.

    A raycast based solution is workable, but it's rather fragile and falls down in a full 3D environment since it erroneously glances geometry at shallow angles.

    I have been experimenting with a stencil buffer based solution which seems incredibly promising but for one hitch.


    The above is exactly the effect I'm trying to achieve. The lens object which faces the camera and is attached to the trolley writes the pixel information early in the queue, and the blocking object reads from it and decides if the pixel needs to be replaced.

    The only issue here, as some of you may have already realised, is that this will cut a hole through every readable object in the scene.


    As you can see, there is actually another object behind the lens that I want to be able to see.

    Is there a way to discard the stencil check for objects that are behind the lens in scene space? Or is there something very simple I'm missing. Does anyone have suggestions on possible solutions?
  2. SM_Ransom


    Dec 20, 2016
    My first suggestion is to try a "stencil clean up" pass.

    This requires an additional draw call, but can make complex stencil ops a little more managable if you're able to afford it. The idea is to do a second draw over the mask after it's done it's job, returning the buffer to a safe value.

    Some other ideas:

    Experiment with the stencil ops & draw order to find a configuration that "consumes" the stencil operation after the desired effect is achieved. Comparison operations like
    can move the Ref value to a safe value. The Mask options can also help you be more specific about what is involved in your stencil op. This can be a little unwieldy.

    You can clear the stencil buffer...of course, that means a clearing operation, which you may want to minimize!