The UI Mask component in Unity’s UGUI system is pretty powerful. If you’re doing any UI work haven’t used the UGUI mask before, make sure to check out the primer video here when you’re done reading this article 🙂
In this article, I’ll show you how to use the UI Mask component for a very specific case, to slide an image over another image.. or to ‘replace an image with another’.
To control the sliding, we’ll use a basic UGUI slider, though you could easily modify the solution to fit any other input source.
UGUI Mask Slider – Setup
To start, create a canvas.
Under the canvas, add a slider & a panel.
Set the panel transform values to match this.
Under the panel, create an image.
Rename the image “Starting Image”
Adjust the rect transform to stretch and fill (hold ctrl/cmd & alt)
Replace the “Source Image” with this image (save it into your project and change the image type to sprite first)
It’s time to create our mask image. To do this create a new image under the panel.
Name it “Mask”
In the Inspector, add a Mask component.
Uncheck the “Show Mask Graphic” box.
The overlayed Image
Under the mask, create the image for the overlay. Name it “Overlayed Image”
Set the “Source Image” to this image and set the rect transform to stretch.
Script Time – Almost Done!
Create a new script named RectTransformLockPosition and replace the contents with this:
Add the RectTransformLockPosition component to the Overlayed Image.
Moving the Mask
Now we need something to move our mask.. we’ve created a slider, but we’ll need a little code too. (in your project you may move this completely different, this is just an example of one way you can move the mask)
Create another script named SlidableMask and replace the contents with this:
Attach the SlideableMask component to the “Mask” gameobject.
Drag the slider in the hierarchy onto the Slider field to assign it. This will link the slider up to the mask. (the code will register the listener for you)
Save and Press Play!
Conclusions & Alternative Methods
You may be wondering if this is the best way to accomplish this effect. Depending on your situation, it may not be, you could get a similar effect from a custom shader or some other cool tricks. But if you’re comfortable with UGUI, it’s an easy and extensible way to replace or reveal an image (or other stuff, no reason you couldn’t have an entire panel of other components back there).
I stumbled across the idea of RectTransformLockPosition on stack overflow or unity answers, but I can’t find the original source. But I still wanted to note it and give credit, so I’m gonna keep searching for that source to share 🙂
Want the project source? You can download it here: https://unity3dcollegedownloads.blob.core.windows.net/vrgames/Masked%20Slider%20Image.zip