Skip to content

UI Masking

Video about it:

If you try to use the asset material on a masked UI element such as the ones contained on a Scroll view you’ll see that the object won’t get masked.

A soldier UI Image inside a Scroll View, drawn over the top edge of the gray area instead of being masked by it

In this image we can see how we have a UI image inside of a Scroll View and it’s not getting masked (it should only be visible inside the gray area). This happens because elements that need to be masked have a unique Stencil configuration, this configuration is not included on the default material since it would bring problems to the regular use cases.

The same cause shows up in the Console as a warning, one per material:

Material <name> doesn't have _Stencil property

Unity’s Mask writes its settings into the material’s _Stencil properties, and the default variant has none. The warning and the element that is not masked go away together, with the UI Mask variant below.

But you can change the shader variant with the shader component and the Image will get masked:

Outlined soldier Images scrolling through a panel with a Mask, twice. With the default variant they draw outside the panel; with the UI Mask variant they are cut off at its edges
The All In 1 Shader component on a UI Image with Change Shader Variant set to Masked UI
The same soldier Image with the UI Mask variant, now cut off cleanly at the top edge of the Scroll View's gray area

Sometimes for this to take effect in the scene you’ll need to Save the scene (Ctrl+S). Same happens when modifying shader properties through the inspector. Another caveat is that, as already mentioned in the Scripting section above you will want to use Image.materialForRendering instead of Image.material when scripting UI Masked UI Images.

For this to work the Stencil buffer must be enabled. In the Built-In pipeline is enabled by default in most platforms. In case you are building for Android you can go to Player Settings, Resolution and Presentation and make sure that the Stencil isn’t disabled.
In URP with the 2D Renderer, the stencil is the Depth/Stencil Buffer checkbox on the 2D Renderer Data asset (Use Depth/Stencil Buffer in older URP versions). It is on by default; make sure it is still ticked:

The AllIn12DRenderer asset in the Inspector, with an arrow pointing at its Use Depth/Stencil Buffer checkbox, ticked