I posted this on Unity Answers but nobody could help me, maybe I’ll have better luck here:
I have a character that’s animated in Spine (3rd party animation software) and exported to Unity, meaning that the output is a textured, meshed object (no sprite renderer).
I now have another GameObject that I want to clip inside the character, meaning it SHOULD draw whenever overlapping parts of the character but NOT when outside the character mesh.
Does anyone have any experience with this and can maybe help? I have thought about buying “Sprite Mask” (from the asset store) but I’m not sure if it would even work for what I need.
The way I’m aware of is having it write to stencil buffer with one shader and read from stencil buffer with the other. I think this would only work in forward rendering though. So an example I use in my project the first would have a shader to set the stencil:
Shader "Sprites/SpritesUnlitStencilSet"
{
Properties
{
[PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
_Color ("Tint", Color) = (1,1,1,1)
[MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
}
SubShader
{
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
"PreviewType"="Plane"
"CanUseSpriteAtlas"="True"
}
Cull Off
Lighting Off
ZWrite Off
Blend One OneMinusSrcAlpha
Pass
{
Stencil {
Ref 254
Comp always
Pass replace
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile _ PIXELSNAP_ON
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
half2 texcoord : TEXCOORD0;
};
fixed4 _Color;
v2f vert(appdata_t IN)
{
v2f OUT;
OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color * _Color;
#ifdef PIXELSNAP_ON
OUT.vertex = UnityPixelSnap (OUT.vertex);
#endif
return OUT;
}
sampler2D _MainTex;
fixed4 frag(v2f IN) : SV_Target
{
fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color;
if (c.a<0.1) discard; //Comment out this line if the mesh doesn't also include transparency
c.rgb *= c.a;
return c;
}
ENDCG
}
}
}
^ Make sure if there is not a transparency in your mesh as is shown above, comment out discard pixels. That is for alpha blending and is slow. If your mesh doesn’t have transparent pixels it is unnecessary.
Once something has set the stencil, you can check the stencil with something like this example:
Unity has built in masking coming in the meantime, which is probably better/faster which I am looking forward to trying, but that would work in the meantime.
Hey, thanks so much for your replies. I am not aiming for mobile devices, PC & Mac only.
I decided to go with “Sprite Mask”, a software from the asset store that basically does what I need out of the box (with stencil buffers). I can only recommend it, it worked like a charm.