68 lines
1.8 KiB
C#
68 lines
1.8 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
|
|
public class DoubleTapButton : MonoBehaviour, IPointerClickHandler
|
|
{
|
|
[SerializeField] private float doubleTapThreshold = 0.25f;
|
|
|
|
// Subscribe bằng code: doubleTapButton.DoubleTapped += () => ...
|
|
public event Action SingleTapped;
|
|
public event Action DoubleTapped;
|
|
|
|
private float _lastTapTime = -999f;
|
|
private bool _waitingSingle;
|
|
private int _tapCount;
|
|
private Coroutine _singleRoutine;
|
|
|
|
public void OnPointerClick(PointerEventData eventData)
|
|
{
|
|
if (eventData.button != PointerEventData.InputButton.Left) return;
|
|
|
|
float now = Time.unscaledTime;
|
|
|
|
if (now - _lastTapTime <= doubleTapThreshold) _tapCount++;
|
|
else _tapCount = 1;
|
|
|
|
_lastTapTime = now;
|
|
|
|
if (_tapCount == 2)
|
|
{
|
|
_tapCount = 0;
|
|
|
|
// huỷ single đang chờ
|
|
_waitingSingle = false;
|
|
if (_singleRoutine != null)
|
|
{
|
|
StopCoroutine(_singleRoutine);
|
|
_singleRoutine = null;
|
|
}
|
|
|
|
DoubleTapped?.Invoke();
|
|
}
|
|
else
|
|
{
|
|
// chờ 1 khoảng để xem có tap lần 2 không, rồi mới fire single
|
|
if (!_waitingSingle)
|
|
{
|
|
_waitingSingle = true;
|
|
_singleRoutine = StartCoroutine(WaitThenSingle());
|
|
}
|
|
}
|
|
}
|
|
|
|
private System.Collections.IEnumerator WaitThenSingle()
|
|
{
|
|
float start = Time.unscaledTime;
|
|
while (Time.unscaledTime - start < doubleTapThreshold)
|
|
{
|
|
if (!_waitingSingle) yield break; // đã double-tap
|
|
yield return null;
|
|
}
|
|
|
|
_waitingSingle = false;
|
|
_singleRoutine = null;
|
|
SingleTapped?.Invoke();
|
|
}
|
|
}
|