Masking UI Elements in Unity 2021

GameDev Dustin
4 min readSep 6, 2022

In this article, we’ll cover using UI Images as masks.

We’ll setup our project with 4 images on a canvas.
Next, we’ll rename two of the images as “Mask1” and “Mask2”.

Then we want to child the remaining two images, one to each mask.

For each child image, we’ll assign a sprite as its Source Image while leaving the “Mask” images without a Source Image.

We’ll also increase our child Images’ dimensions to be 200 x 200 rather than 100 x 100.

Now, let’s add the “Mask” component to the “Mask1” image element.

If we drag around Mask1’s child image element, we can clearly see that any part of the child image that does not fit in our mask is culled from being rendered.

For demonstration purposes, let’ set the Mask1 source image as a sprite that looks like a background and its child image’s source image as something we’d expect to be rendered in front of a background

Now we should have something similar to that shown above.

Let’s resize our child image of Mask1 to 50 x 50 or whatever is necessary to make your sprite smaller than the Mask1’s dimensions.

Now, drag the child image of Mask1 around and observe the behavior.

This could be a useful approach if you need to make something seem like it is coming from “off-screen” as it were.

Only, instead of the entire game screen, this could be used on a 3D game object such as a TV or Monitor where you are animating or at least showing images.

That is only one use-case though, who knows how many more there could be.

On our “Mask” component of the Mask1 Image element, we can toggle a field named “Show Mask Graphic”.

Essentially, we end just turned off the image for the Mask1 image element.

There is another approach that does not require the Image component (sprite) on our Mask Image element.

On the “Mask2” Image element, disable the “Image” component entirely.

Add the “Rect Mask 2D” component to Mask2.

I’ve also changed the child image to match our other child image for clarity.

We can see that we get the same effect without using an Image (sprite) based component.

Now, our Rect Mask 2D has additional settings our normal Mask component did not have.

Let’s set our child Image dimensions to 200 x 200 so that it is larger than the Mask2 element.

Now, on the Mask2 element’s Rect Mask 2D component, play with the padding and softness values to get a feel for their effects.

But what if we want the benefits of Rect Mask 2D and an Image?
Not an issue, just leave the Image component as enabled.

To better illustrate, add a sprite to the Mask2 Source Image field.

I hope you enjoyed this article, we’ll see you in the next!

--

--