我有一个 OnPointerClick() 函数,如果我连续点击多个按钮,有时会被触发两次,即使我只按了这个按钮一次。这发生在新的输入 UI 系统中。我该如何阻止这种情况发生?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ClickableButtons : MonoBehaviour, IPointerClickHandler {
public void OnPointerClick (PointerEventData eventData) {
Debug.Log("Clicked"); //Called twice most of the time when button is pressed once
}
}
首先,在造成2次点击的原因之前,我们先尝试解决2次点击造成的问题。因为你提供的信息不够。
public class ClickableButtons : MonoBehaviour, IPointerClickHandler
{
private static readonly object ClickLock = new object();
public void OnPointerClick(PointerEventData eventData)
{
lock (ClickLock)
{
Debug.Log("Clicked"); //Called twice most of the time when button is pressed once
}
}
}
如果将单击后要执行的操作放在“锁定”语句中,则会阻止这些操作同时执行。
public class ClickableButtons : MonoBehaviour, IPointerClickHandler
{
private static readonly object ClickLock = new object();
private bool clicked = false;
public void OnPointerClick(PointerEventData eventData)
{
if (clicked) return;
lock (ClickLock)
{
clicked = true;
Debug.Log("Clicked"); //Called twice most of the time when button is pressed once
clicked = true;
}
clicked = false;
}
}
你可以尝试用“if”语句来控制它。 但我想知道为什么不使用按钮的 onclick 事件?
https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Button-onClick.html
如果有人偶然发现这一点,则场景中拥有超过 1 个 EventSystem 可能会导致这种情况发生。包括任何来自 Rewired 等资产的内容!
我的场景中不小心有超过 1 个 EventSystem。