askvity

How do I add a mask to an image in Unity?

Published in Unity UI Masking 3 mins read

To add a mask to an image in Unity, you can use a Panel and a Mask component. Here's a step-by-step guide:

Steps to Apply a Mask in Unity

  1. Create a Panel: Begin by creating a new Panel object in your Unity scene. You can do this by right-clicking in the Hierarchy window and selecting UI > Panel. The Panel will serve as your mask shape.
  2. Add an Image as a Child: Create an Image object and make it a child of the Panel you just created. This image will be the one that gets masked. You can do this by right-clicking on the Panel in the Hierarchy and selecting UI > Image.
  3. Position the Image: Position the Image so that the part you want to show through the mask is directly behind the Panel area. Essentially, the area of the Image visible through the Panel will be the only visible portion after the mask is applied.
  4. Add the Mask Component: Now, select the Panel object in the Hierarchy. In the Inspector window, click the "Add Component" button and search for "Mask". Add the Mask component to the Panel. This component makes the Panel act as the masking area.

How It Works

Here’s a breakdown of how this method functions:

  • The Panel acts as the mask's shape. The dimensions and shape of the Panel determine the area of the underlying Image that will remain visible.
  • The Image is positioned behind the Panel, and the Mask component on the Panel hides anything outside of the Panel's bounds.
  • The Mask component renders only the parts of the Image that overlap with the Panel and hides everything else.

Example

Let's say you have an image of a landscape and you want to show only a circular portion of it.

  1. Create a Panel and shape it into a circle (you can use a circle sprite for the Panel's source image).
  2. Add your landscape Image as a child of this circular Panel.
  3. Position the landscape Image so that the area you want to show through the circle is aligned behind the circle Panel.
  4. Add the Mask component to the circle Panel.

Now, only the part of your landscape image that is behind the circle will be visible.

Table Summary

Component Purpose Hierarchy Position
Panel Acts as the mask shape Parent
Image The image that will be masked Child of Panel
Mask Component on the Panel that applies the masking Added to Panel

This simple technique allows you to easily control which parts of an Image are visible in your Unity project using a mask.

Related Articles