UnknownUser
UnknownUser

Reputation: 327

How to fix in-game double-click issue in Unity?

I have this issue with double clicking in-game. I wrote this code that checks for input and returns the type of input it received.

In editor it works just fine, but when I export the game it always returns double click type. Even if I click just once. Not sure what's causing this issue..

Below is the mouse input script and other is how I use it in other scripts.

Mouse Input script:

using System.Collections;
using UnityEngine.EventSystems;

public class MouseInput : MonoBehaviour
{
    #region Variables

    private enum ClickType      { None, Single, Double }

    private static ClickType    currentClick    = ClickType.None;
    readonly float              clickdelay      = 0.25f;

    #endregion

    void OnEnable()
    {
        StartCoroutine(InputListener());
    }
    void OnDisable()
    {
        StopAllCoroutines();
    }

    public static bool SingleMouseClick()
    {
        if (currentClick == ClickType.Single)
        {
            currentClick = ClickType.None;
            return true;
        }

        return false;
    }
    public static bool DoubleMouseClick()
    {
        if (currentClick == ClickType.Double)
        {
            currentClick = ClickType.None;
            return true;
        }

        return false;
    }

    private IEnumerator InputListener()
    {
        while (enabled)
        {
            if (Input.GetMouseButtonDown(0))
            { yield return ClickEvent(); }

            yield return null;
        }
    }
    private IEnumerator ClickEvent()
    {
        if (EventSystem.current.IsPointerOverGameObject()) yield break;

        yield return new WaitForEndOfFrame();

        currentClick = ClickType.Single;
        float count = 0f;
        while (count < clickdelay)
        {
            if (Input.GetMouseButtonDown(0))
            {
                currentClick = ClickType.Double;
                yield break;
            }
            count += Time.deltaTime;
            yield return null;
        }
    }
}

Usage:

if (MouseInput.SingleMouseClick())
{
    Debug.Log("Single click");
    Select(true);
}
else if (MouseInput.DoubleMouseClick())
{
    Debug.Log("Double click");
    Select(false);
}

Upvotes: 0

Views: 2493

Answers (1)

Foggzie
Foggzie

Reputation: 9821

So on the frame Input.GetMouseButtonDown(0) evaluates to true you call into ClickEvent() which then yields on WaitForEndOfFrame(); then eventually gets back to another Input.GetMouseButtonDown(0)).

You problem is that WaitForEndOfFrame() waits until the end of the current frame:

Waits until the end of the frame after all cameras and GUI is rendered, just before displaying the frame on screen.

It doesn't wait until the next frame. Because of this, all values returned by the Input API are still going to be the same. You want a yield return null instead of WaitForEndOfFrame().

Upvotes: 1

Related Questions