Search code examples
c#unity-game-enginegraphicsmaskunity-components

How do I mask a custom UI Graphic in Unity?


In Unity 2017, I've managed to draw vector graphics by making my own UI behaviors that inherit from UnityEngine.UI.Graphic. But my code is irrelevant because you can observe this problem just as well using the SimpleImage example from the documentation. The problem is that these custom UI behaviors that derive from Graphic can't be masked by a Mask component, even though every native UI element can be. This is very strange because according to the Graphic.OnPopulateMesh documentation, Text, Image, and RawImage all use this same method.

To reproduce:

  1. Create a UI Canvas.
  2. Create a UI Image named Mask as a child of the UI Canvas.
  3. Add a Mask component to the Mask game object.
  4. Add an Image and a SimpleImage as children of Mask.
  5. Observe that the Image is masked while the SimpleImage is not.

This is a problem for me because I need to use custom graphics in Scroll Views. What can I do to make my graphics maskable the same as Unity's graphics?


Solution

  • I figured this out right as I finished typing it. It's ridiculously easy. All you have to do is inherit from MaskableGraphic instead of Graphic.