Sprite masking is a really useful feature of unity. It enables us to view one sprite at a time when there are overlapping sprites in the scene view.
It is really useful in making detective, strategy and even some logic based games.
This article explains you the usage of Sprite masking when working with sprites in unity.
Consider the following scenario, where we have an opaque block and a shape hidden behind it. We are provided with a magnifying glass that we can use to see through to identify which shape is hidden behind the opaque block.
For this demo, we will need three sprites:
1. An opaque block
2. A shape to hide behind the block (the Unity logo)
3. A magnifying glass that we can use to see through the opaque block (we call it mask)
Here are the assets you will require for this demonstration.
Step 1: Import the sprites in unity in a folder named Sprites and place them over one another as in the image below.
Don’t worry which one is at the top. Just place then one over the other like the image below.
Step 2: If the Unity logo is not hidden behind the opaque red block, select the Opaque block in the Project Hierarchy & in the inspector view, under Sprite Renderer, change the value of “Order In Layer” to 1. This will hide the logo behind the opaque block.
If the Unity logo is already hidden behind the opaque red block, jump directly to Step 3.
Step 3: In the Hierarchy view, right click on the Hidden Image & select “2D Object” => “Sprite Mask”
This will create a sprite mask under the Hidden image.
Now rename the New Sprite Mask to SpriteMask
Step 4: With SpriteMask selected, in the inspector view, drag & drop the mask on Sprite under Sprite Mask.
Step 5: In the Inspector view, select the Hidden image. Under the Sprite Renderer in the inspector view, change the value of Mask Interaction to Visible Inside mask. Now select the Opaque Block and under Sprite Renderer in the inspector view, change the value of Mask Interaction to Visible Outside mask.
With SpriteMask selected, move the mask with the move tool. You will see the Sprite Masking in action.