C# – Mouse up vs. touch up in Unity

ciosnetunity3dunity5

I have a bit of an issue. I can't seem to find a good way to distinguish whether Unity is firing a mouse up vs. a touch up event. By touch up I mean when the user releases their finger from the screen after touching something on a touch display.

The problem is this: I have an issue with game logic where the user both lets go of something they've selected with their mouse and SIMULTANEOUSLY touches / releases their touch to click a UI button (in other words, I'm trying to detect a mouse release only, or, a touch release only – how can I do that?). I've tried using both Input.GetMouseButtonUp(0) as well as Input.GetMouseButton(0), but both change their state if its a touch up or a mouse button up event.

So how do you properly distinguish between the two? I even tried using the Touch.fingerId property which works well to track / distinguish ONLY touch events, but, the problem is then that I still cannot distinguish ONLY mouse up with Input.GetMouseButton(0) since it fires even in the event of a touch up.

Does anyone out there happen to know what the proper way would be to detect just a mouse release, or just a touch release, separately, in Unity?

Edit:

Someone didn't understand the problem at hand, so let's assume for a second you have a desktop device with touch support. Add this script:

void Update () {
    if (Input.GetMouseButtonDown(0))
        Debug.Log("Mouse button down.");
    if (Input.GetMouseButtonUp(0))
        Debug.Log("Mouse button up.");
}

If you click and HOLD with your mouse, while holding, you can touch and release with your finger, which will log Mouse button up., despite the fact that you did not release the mouse button. How can I distinguish between a mouse up vs. a touch release?

Best Answer

For desktops:

  • Mouse Down - Input.GetMouseButtonDown
  • Mouse Up - Input.GetMouseButtonUp

Example:

if (Input.GetMouseButtonDown(0))
{
    Debug.Log("Mouse Pressed");
}

if (Input.GetMouseButtonUp(0))
{
    Debug.Log("Mouse Lifted/Released");
}

For Mobile devices:

  • Touch Down - TouchPhase.Began
  • Touch Up - TouchPhase.Ended

Example:

if (Input.touchCount >= 1)
{
    if (Input.touches[0].phase == TouchPhase.Began)
    {
        Debug.Log("Touch Pressed");
    }

    if (Input.touches[0].phase == TouchPhase.Ended)
    {
        Debug.Log("Touch Lifted/Released");
    }
}

Now, if you are having issues of clicks going through UI Objects to hit other Objects then see this post for how to properly detect clicks on any type of GameObject.