I have an OnPointerClick() function that sometimes gets fired twice if I keep clicking on multiple buttons at a stretch, even though I have pressed this button only once. This is happening in the new Input UI System. How do I stop this from happening?
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
}
}
CodePudding user response:
First of all, let's try to solve the problem caused by 2 clicks, before the causes of 2 clicks. Because the information you provide is not enough.
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
}
}
}
If you put the actions to be performed after the click in the "lock" statement, it will prevent the actions from being done at the same time.
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;
}
}
You can try to control it with an "if" statement. But what I'm wondering is why don't you use the button's onclick event?
https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Button-onClick.html