Unity: Button Hit Detection

This article covers Unity’s button detection issues when using Unity’s Canvas button with raycasting for button detection.

A little background before we delve into the issue. Unity’s Canvas allows responsive UI design. If your target platforms will be different aspect ratios and resolutions. Using Unity’s Canvas is your answer. Our game was going to be deployed on many different screens. So, we used the Canvas for our UI.

While testing out button responses, I noticed our buttons were enabled and working even if I wasn’t clicking on the button. Now usually we have some kind of collider system to deal with this and we just update that to fix this issue. Like move the bounds of the collider or update it’s shape.

Canvas however, doesn’t use colliders.

It uses a raycast method, to detect mouse input. I believe, this is something similar to Maya’s mouse detection. I remember how this worked because of a tool I made in Maya to calculate distances. Like a ruler for Maya. Maya uses a raycast method to detect a hit in 3D space of the mouse click on a monitor which is X,Y 2D plane.


Now that I knew where to find the fix, I started investigating Unity’s raycast detection.

Before, I go to the fix. This is the problem we were facing.

Button getting detected out of bounds.

Here you can see the button getting detected even when I click outside the button. Looking at this, I thought the Sprite outline which makes the sprite mesh needs to be updated. But that had no effect on the outcome and we also wanted to keep a full rect for the sprite mesh anyway.


Solution…

Luckily, with just a few searches we found out that this is a common issue. The fix was very simple and described in Unity’s documentation.

We needed to call a method “alphaHitTestMinimumThreshold” of the Image class in Unity’s UnityEngine.UI namespace.

The script to fix the issue.

Here’s the link: https://docs.unity3d.com/2018.1/Documentation/ScriptReference/UI.Image-alphaHitTestMinimumThreshold.html


Add this script on the button gameobject to set the Canvas Renderer’s Image Alpha Test Minimum Threshold. Then, once the minimum value is set, the Alpha test will not detect touch for anything below that value.

So in our case, since the circle image was imported with 100% alpha outside the circle. We set the threshold to 0.1.

Button detection working correctly.
Testing the fix on hover to show detection bounds are working properly.

Important Note for using the above solution…

This method can only work if the image property is set to Read and Write Enabled.