Search code examples
c#unity-game-engineunity-ui

How to have event onPointerUp register regardless of if OnPointerDown was registered


Currently, I'm working on a mobile game where the user will click and drag something in the environment, and if they drag it to the center it will open a fan menu, where they can then select an option. The problem I have, is the user's finger will still be pressed when the menu opens and if they drag their finger over a menu item and then release it won't register an OnPointerUp event.

It would ruin the UX of this part of my game to force the user to let go of the screen and press on a menu item because it is supposed to be a smooth transition from dragging an element.

The event does register if I initially press on one of my UI elements, and then move my finger to a different one then let go, but it doesn't work from an OnPointerDown originating outside of my buttons.


Solution

  • You can change the object that received the OnPointerDown event by changing the pointerPress variable of the Event Data.

    The following script will trigger OnPointerUp to any objects you release the pointer on:

    public class TestUI : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler
    {
        public void OnPointerDown(PointerEventData eventData) { Debug.Log(this.gameObject + " Down"); }
        public void OnPointerEnter(PointerEventData eventData) { eventData.pointerPress = gameObject; }
        public void OnPointerUp(PointerEventData eventData) { Debug.Log(this.gameObject + " Up"); }
    }