如何修复 Unity 中的游戏内双击问题?

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

我在游戏中双击时遇到了这个问题。我编写了这段代码来检查输入和 returns 它收到的输入类型。

在编辑器中它工作得很好,但是当我导出游戏时它总是 returns 双击类型。即使我只点击一次。不确定是什么导致了这个问题..

下面是鼠标输入脚本,其他是我在其他脚本中使用它的方式。

鼠标输入脚本:

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;
        }
    }
}

用法:

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

所以在框架 Input.GetMouseButtonDown(0) 上评估为真,你调用 ClickEvent() 然后在 WaitForEndOfFrame(); 上产生然后最终返回到另一个 Input.GetMouseButtonDown(0)).

你的问题是WaitForEndOfFrame()等到当前帧结束

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

它不会等到下一帧。因此,Input API 返回的所有值仍然相同。你想要 yield return null 而不是 WaitForEndOfFrame().