Is stencil command on Unity used only for making pixels invisible or is it more?

Viewed 476

I want to have an object which is greyed out (grayscale) when it is inside a specific mesh. For now, I have followed some videos and used the stencil command in shader to make it invisible inside (or outside) the mesh but this is not what I quite want.

How can I make it so the object will be seen as it is when inside a specific mesh renderer and have a grayscale effect when outside it? Is it possible to do that using stencil on Unity shaders?

1 Answers

Unity - Sharderlab - Stencil

The stencil buffer stores an 8-bit integer value for each pixel in the frame buffer. Before executing the fragment shader for a given pixel, the GPU can compare the current value in the stencil buffer against a given reference value. This is called a stencil test. If the stencil test passes, the GPU performs the depth test. If the stencil test fails, the GPU skips the rest of the processing for that pixel. This means that you can use the stencil buffer as a mask to tell the GPU which pixels to draw, and which pixels to discard.

and in general more about it e.g. at Wikipedia - Stencil Buffer.

In very simplified words: Basically it is used to tell the Shader passes to not overwrite certain pixels based on given conditions and allows them to write a certain value to the stencil buffer for the rendered pixels themselves.

See Through Objects with Stencil Buffers using Unity URP is a good explanation and example use case.


For your specific use case

How can I make it so the object will be seen as it is when inside a specific mesh renderer and have a grayscale effect when outside it?

you might want to have a look at Creating Overlap Shader Effects, Such as Underwater and Night Vision, in Unity's Shader Graph which rather uses the ShaderGraph and a Depth test.

Related