Prevent Double Clicking Unity Buttons on Mobile
Do you know, that we can double-fire the event of a simple Unit Button on Mobile? Yes, you can click the button with 2 fingers and the onCall
callback will be called 2 times. This caused some serious issues with my first game. Based on how you implement the callback logic on the button you might encounter similar bugs. I’ve found this workaround. Inherit your own “mobile safe” Button class and start using that. A drawback is that you have to change all the components to MobileButton explicitly, but it will have the same properties. It should work with a mouse click and with only the first finger. Take a look at the script:
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[AddComponentMenu("UI/MobileButton", 30)]
public class MobileButton : Button
{
public override void OnPointerClick(PointerEventData eventData)
{
if (eventData.pointerId == 0 || eventData.pointerId == -1)
{
onClick?.Invoke();
}
}
}
}