Search code examples
c#unity-game-engineonmouseup

Can you get finger position from OnMouseDown and OnMouseUp?


On a 2D layout, having a fixed in place button-like GameObject that has a script with the OnMouseDown and OnMouseUp function: touching that and moving the finger away and releasing, can that OnMouseUp get that corresponding finger release position on screen?

The catch is: its a multiplayer, many other fingers on screen!


Solution

  • You shouldn't be using the OnMouseDown and OnMouseUp callback functions for this because that would require that you get the touch position with Input.mousePosition on the desktops and Input.touches on mobile devices.

    This should be done with the OnPointerDown and OnPointerUp functions which gives you PointerEventData as parameter. You can access the pointer position there with PointerEventData.position. It will work on both mobile and desktop devices without having to write different code for each platform. Note that you must implement the IPointerDownHandler and IPointerUpHandler interfaces in order for these functions to be called.

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("Mouse Down:  " + eventData.position);
    }
    
    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("Mouse Up: " + eventData.position);
    }
    

    If you run into issues with it, you can always visit the troubleshooting section on this post to see why.