Using Stencil Shader to mask object, regardless of being occluded by mask in Unity URP

103 Views Asked by At

I'm working in Unity URP, and I'm unfortunately struggling a bit with stencil shaders. I was wondering if someone would be able to identify where I'm making a misstep:

Essentially, what I'm trying to achieve is for the green box to only be visible when within the silhouette of the red sphere, even if the masking object, the red sphere, is occluding it. Currently, the green box will be covered by the masking object, as seen in the GIF:

masked object is occluded by masker

The following is my shader code:

Red Sphere

Shader "Red" {
    SubShader {
        Tags { "RenderType"="Opaque" "Queue"="Geometry-1"}
        Pass {
            Stencil {
                Ref 1
                Comp always
                pass replace
            }

Green Cube

Shader "Green" {
    SubShader {
        Tags { "RenderType"="Opaque" "Queue"="Geometry"}
        Pass {
            Stencil {
                Ref 1
                Comp equal
            }

My desired result would be that the green is visible, even when behind the mask object, as in this GIF: green always appears in front of mask object

The results in that GIF were achieved by addingztest always to the subshader, but I unfortunately had to undo that code, since it would make the mask appear in front of all world objects. ztest issue

Do you have any pointers or solutions to this issue I'm experiencing? I'm not experienced with shader coding, so it's been a lot of trial and error.

I've tried to use ztest always on the green shader, but unfortunately this caused the green to be visible through any game world object, as seen in the prior gif. My desired result would be that the green is only visible when within the silhouette of the mask, but that also any other world object can occlude it as normal.

1

There are 1 best solutions below

0
MartinTriesIt On

Update!

The answer to my specific issue was that a "ztest NotEqual" should be added to the green shader, and that the green shader should be higher in the Queue than the red shader. Now it works perfectly