Q: How do I make a custom clickable shape for a button?
Answer:
Use the Set Property action to set the alphaHitTestMinimumThreshold property on an Image component:
https://docs.unity3d.com/ScriptReference/UI.Image-alphaHitTestMinimumThreshold.html
This lets you use the sprite's alpha channel when hit testing the button.
Note: In Unity 5.3 the property was called: eventAlphaThreshold
Example Setup
Let's say you have a Star sprite you want to use as a Button:
1. Setup the Star Sprite's import settings:
- Select the Sprite asset in the Project View.
- The Inspector shows the Import Settings.
- Under Advanced, check Read/Write Enabled.
- Also make sure the sprite is not Packed.
NOTE: In older versions of Unity, these settings are under Texture Type: Advanced.
2. Use the Star Sprite in the Button:
- Select the Button and find its Image component.
- Use the Sprite as the Source Image.
- Adjust the Button's Width and Height (e.g., 100 x 100)
3. Use the Set Property action to set the Image alphaHitTestMinimumThreshold.
- Add an FSM to the Button and select the Start State.
- Drag the Button's Image component into the State panel.
- From the popup menu select Set Property.
- Select the alphaHitTestMinimumThreshold property.
- Set the value to 0.5.
Note: You can also add the Set Property action from the Action Browser and set it up manually. Drag and dropping the component just saves you a couple of steps!
4. Now when you press Play, only the solid part of the star should be clickable!
Notes
- This kind of hit-testing is a little more expensive than rectangular hit testing.
- Set Property is slower than a custom action, but in this kind of situation where you're doing something once (not every frame) it really won't be noticeable.
- Since making this tutorial Jean added a uGuiSetImageAlphaTestThreshold to the PlayMakerEcosystem.