Skip to content

Instantly share code, notes, and snippets.

@ewandennis
Created January 2, 2018 20:42
Show Gist options
  • Save ewandennis/ff0f12da482a0aff55486290c00c5e9e to your computer and use it in GitHub Desktop.
Save ewandennis/ff0f12da482a0aff55486290c00c5e9e to your computer and use it in GitHub Desktop.
A simple stencil buffer masking shader for Unity
Shader "Custom/StencilMask" {
Properties {
_StencilMask("Stencil mask", Int) = 0
}
SubShader {
Tags {
"RenderType" = "Opaque"
"Queue" = "Geometry-100"
}
ColorMask 0
ZWrite off
Stencil {
Ref[_StencilMask]
Comp always
Pass replace
}
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct appdata {
float4 vertex : POSITION;
};
struct v2f {
float4 pos : SV_POSITION;
};
v2f vert(appdata v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}
half4 frag(v2f i) : COLOR {
return half4(1, 1, 0, 1);
}
ENDCG
}
}
}
@michaelSAE
Copy link

works great.. thx heaps

@RandomVariable1470
Copy link

Will this work for urp?

@ewandennis
Copy link
Author

Good question @RandomVariable1470 - I wrote this a long time ago as an experiment. I haven’t maintained it since I’m afraid. If you find out , let us know!

@bboz87
Copy link

bboz87 commented Jun 26, 2024

If you are using URP and the masking effect isn't happening, or your stencil shaders are giving a parse error claiming there is an unexptect "}", you can fix it by creating a new URP shader graph (if this is for the stencil object shader, set up sprite color & alpha outputs from _MainTex inside the shader graph editor, so that the resulting material can get the color of your main texture), click on "View Generated Shader" in the inspector, copy the generated codes from the shader graph to your .shade file, then make the subshader edits here. As long as both of your shaders are URP, things will work properly.
@RandomVariable1470

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment