[Solved] Preventing button onClick event if player moved cursor while clicking inside button

What it should do is check to see how much the player has moved the cursor / finger when tapping / clicking and if he moved it too much, don’t do anything but it’s not working: the button’s onClick event is always getting fired.

The code:

using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace MyUI
{
    [RequireComponent(typeof(Button))]
    public sealed class FixedButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    {
        [SerializeField] private float _sensitivity;
        [NonSerialized] private Vector2 _initialPointerPosition;

        void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
        {
            _initialPointerPosition = eventData.position;
        }

        void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
        {
            var distance = Vector2.Distance(_initialPointerPosition, eventData.position);
            Debug.LogFormat("Distance is {0}.", distance);
            if (distance > _sensitivity)
            {
                eventData.Reset();
            }
        }
    }
}

try

eventData.eligibleForClick = false;

instead of

eventData.Reset();

The StandaloneInputModule calls OnClick immeadiately after OnPointerUp and only checks if the PointerEventData is elegible for clicking (that and if its calling on the same gameobject). In this case, Resetting the event (or even using for that matter) won’t prevent the module from calling OnClick once OnPointer has already been called.

1 Like

Thanks that solved it!