- Home /
How can I change the Unity 5 UI hitbox/collider to fit my complex image?
Hello! I have been updating my game to unity 5 and in doing so have remade my previous GUI using the new Unity UI system. I move my character by casting a physics raycast on click to get a location on the ground and then my character moves to that location. After adding the HUD element shown below I block a lot of my screen from being clicked. I do want the wooden portion of the image to block ray casting but not the area I've colored red. i am using a "Raw Image" within the canvas. I have tried multiple solutions:
Editing the Physics shape and the outline in the Sprite editor
Tuning off "Raycast Target" option in the Raw Image component and adding a Polygon Collider 2D with a Rigid body 2D
Casting my own graphics raycast and using a list of all objects hit to see if I've clicked it but this doesn't follow the collider
None of these solutions have solved my problem, I have other UI elements that don't have concave shapes and they work wonderfully but I am struggling with this. Any help would be greatly appreciated!
Image with red showing where i want to be able to click:
Physics Shape:
Answer by troien · Nov 24, 2017 at 01:59 PM
In theory, using Image.alphaHitTestMinimumThreshold would be the easiest way. I believe it wasn't implemented in older versions of Unity. It is now as I just checked.
Using it would be something like this:
using UnityEngine;
using UnityEngine.UI;
public class Example : MonoBehaviour
{
private void Awake()
{
Image image = GetComponent<Image>();
image.alphaHitTestMinimumThreshold = 0.1f;
}
}
Note however that your sprite has to be setup correclty for this to work.
In order for greater than 0 to values to work, the sprite used by the Image must have readable pixels. This can be achieved by enabling Read/Write enabled in the advanced Texture Import Settings for the sprite and disabling atlassing for the sprite.
What I had to do to get this to work was:
On the sprite, check read/write enabled (this is hidden under a advanced dropdown halfway the settings)
In the sprite, set Mesh Type to 'Full Rect' instead of 'Tight'
You might need to change some other settings aswell.
There is also a way by implementing ICanvasRaycastFilter.IsRaycastLocationValid. I had an older answer from when Unity UI was just released explaining this. Can't find it anymore though :(
Your answer
