Unity Tricks — How to hide a UI object that is behind a transparent UI?

Longchang Cui
3 min readSep 6, 2020

--

Example

When I was developing a progress bar, I encountered a UI problem that was a bit challenging to solve. As you can see from the image below, the progress line is overlapping with the ring UI. Of course, there’s an easy way to solve this by simply adding a UI object on top of the ring that has the same color as the background. But we can handle this problem in an elegant way by using shaders.

UI Problem

Step 1: Create Shaders

1–1: Create an Unlit Shader and name it TransparentHideShader

1–2: Create a Standard Surface Shader and name it TransparentCoverShader

Now, you should have two shaders. TransparentCoverShader and TransparentHideShader

Step 2: Shader Code

2–1: Open TransparentCoverShader and copy/paste the shader code below. Then, save it.

2–2: Open TransparentHideShader and copy/paste the shader code below. Then, save it.

Step 3: Create Materials

Create Materials and name them TransparentCoverMat and TransparentHideMat respectfully.

Now, you should have 2 materials.

Step 4: Assign Shaders to Materials

4–1: Select TransparentCoverMat in the Assets folder, and assign Custom/TransparentCoverShader in the Inspector

In the Inspector, click Shader -> Select Custom -> Select TransparentCoverShader

4–2: Similarly, select TransparentHideMat in the Assets folder, and assign Custom/TransparentHideShader in the Inspector

In the Inspector, click Shader -> Select Unlit-> Select TransparentHideShader

Step 5: Assign Materials to UI

5–1: Assign the TransparentCoverMat to the UI object that you want to cover (Treat it as a mask). In my case, it’s a circle image.

5–2: Assign the TransparentHideMat to the UI object that you want to hide. In my case, it’s a line image.

5–3: Make sure to add a UI under the circle cover object. Because the circle cover should be invisible from the game view at the moment.

5–4: Arrange the circles and the line. Make sure the line object is placed below the circle objects.

Here’s the final layout!

This trick is extremely helpful when you develop 2D games. It can be used in various scenarios. Hope this trick will help you figure out some other challenging problems.

--

--