我是新来的,我正在与 UNITY 一起开始我的冒险。我的双击事件有问题。我想在我的商店购买或出售东西。当我早些时候在统一(
public Button button;
)上分配一个按钮时,它可以工作。但是当我尝试对“开始”和“更新”方法上的按钮进行此更改时:
void Start () {
button = GameObject.Find(EventSystem.current.currentSelectedGameObject.name).GetComponent<Button>();
button.onClick.AddListener(ButtonListner);
}
void Update()
{
button = GameObject.Find(EventSystem.current.currentSelectedGameObject.name).GetComponent<Button>();
}
private void ButtonListner()
{
counter++;
if (counter == 1)
{
StartCoroutine("doubleClickEvent");
}
}
IEnumerator doubleClickEvent()
{
yield return new WaitForSeconds(clickTimer);
if (counter > 1)
{...}
不幸的是,doubleClickEvent() 方法不起作用...... 我该怎么办?问候;)
我注意到的第一件事是:
button = GameObject.Find(EventSystem.current.currentSelectedGameObject.name).GetComponent<Button>();
EventSystem.current.currentSelectedGameObject
属性可以随时为null
,尤其是在第一帧中,这意味着在Start
函数中使用它不是一个好主意。找到 Button
游戏对象,然后从中获取 Button
组件:
Button button;
void Start()
{
button = GameObject.Find("YourButtonName").GetComponent<Button>();
button.onClick.AddListener(ButtonListner);
}
将
"YourButtonName"
替换为您的 Button
游戏对象的名称。
PointerEventData.clickCount
函数中使用 OnPointerClick
获取双击或点击计数。您必须实现 IPointerClickHandler
接口才能正常工作。
只需附加到
Button
游戏对象即可:
public class ClickCountDetector : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
int clickCount = eventData.clickCount;
if (clickCount == 1)
OnSingleClick();
else if (clickCount == 2)
OnDoubleClick();
else if (clickCount > 2)
OnMultiClick();
}
void OnSingleClick()
{
Debug.Log("Single Clicked");
}
void OnDoubleClick()
{
Debug.Log("Double Clicked");
}
void OnMultiClick()
{
Debug.Log("MultiClick Clicked");
}
}
您可以在没有协程的情况下检测双击,如下所示:
// Choose the time you want between clicks to consider it a double click
float doubleClickTime = .2f, lastClickTime;
void Update()
{
// Checking left mouse button click, you could choose the input you want here
if (Input.GetMouseButtonDown(0))
{
float timeSinceLastClick = Time.time - lastClickTime;
if (timeSinceLastClick <= doubleClickTime)
Debug.Log("Double click");
else
Debug.Log("Normal click");
lastClickTime = Time.time;
}
}
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class DoubleClickButton : MonoBehaviour
{
[Header("Click Intervar")]
[SerializeField] private float interval = 0.4f;
[Space(10)]
[SerializeField] private UnityEvent doubleTapEvent;
private void Awake()
{
GetComponent<Button>().onClick.AddListener(OnClick);
}
private float lastClick = 0f;
private void OnClick()
{
if ((lastClick + interval) > Time.time) doubleTapEvent?.Invoke();
lastClick = Time.time;
}
}
这是 Unity 中的一个奇怪问题,但是...这是一个简单的问题...可以通过添加和删除侦听器来解决。这应该有效。
private void OnEnable()
{
button.onClick.AddListener(ButtonListner);
}
public void OnDisable()
{
button.onClick.RemoveListener(ButtonListner);
}