【问题标题】:How to fix in-game double-click issue in Unity?如何解决 Unity 中的游戏内双击问题?
【发布时间】:2019-08-13 20:52:01
【问题描述】:

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

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

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

鼠标输入脚本:

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

【问题讨论】:

    标签: c# unity3d input mouse double-click


    【解决方案1】:

    因此,在框架上 Input.GetMouseButtonDown(0) 评估为 true,您调用 ClickEvent(),然后在 WaitForEndOfFrame(); 上产生,然后最终返回到另一个 Input.GetMouseButtonDown(0))

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

    等到所有相机和 GUI 完成后的帧结束 渲染,就在屏幕上显示帧之前。

    它不会等到下一帧。因此,Input API 返回的所有值都将保持不变。您需要 yield return null 而不是 WaitForEndOfFrame()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-01
      • 2021-05-28
      相关资源
      最近更新 更多