Stencil Buffer Magic

Here’s how I used Stencil Buffers and URP’s Forward Renderer features in Unity to create a spawn animation for my space shooter game. An early version of this game is playable on my itch.io.

I use stencil buffers to spawn enemy packs out of thin air and here is how it looks in-game:

In order to achieve this effect, I created this shader;

Shader "Stencil"
{
	Properties
	{
		[IntRange] _StencilID("Stencil ID", Range(0, 255)) = 0
	}
		SubShader
	{
		Tags
		{
			"RenderType" = "Opaque"
			"Queue" = "Geometry"
			"RenderPipeline" = "UniversalPipeline"
		}

		Pass
		{
			Blend Zero One
			ZWrite Off

			Stencil
			{
				Ref[_StencilID]
				Comp Always
				Pass Replace
				Fail Keep
			}
		}
	}
}

I placed all the objects of type Enemy on a newly created Stencil1 layer.


I created two forward renderer features, one for opaque objects and one for transparent. Note that I used the Stencil1 layer as the layer mask.


I created a new material using the Stencil shader I wrote, paying attention to use the same Stencil ID I used when adding the renderer feature in the previous step.


I then assigned this material to a sphere and animated its scale, along with some other properties, to create the illusion of enemies appearing out of nowhere. Here is how it looks in the editor.

And here’s how it looks in game: