| | 1 | | using Cysharp.Threading.Tasks; |
| | 2 | | using System; |
| | 3 | | using System.Threading; |
| | 4 | | using UnityEngine; |
| | 5 | | using UnityEngine.UI; |
| | 6 | |
|
| | 7 | | [RequireComponent(typeof(Button))] |
| | 8 | | public class ButtonDoubleClick : MonoBehaviour, IButtonDoubleClick |
| | 9 | | { |
| | 10 | | public event Action OnClick; |
| | 11 | | public event Action OnDoubleClick; |
| 68 | 12 | | public bool AlwaysPerformSingleClick { get; set; } = false; |
| | 13 | |
|
| | 14 | | private Button button; |
| 66 | 15 | | private CancellationTokenSource cts = new CancellationTokenSource(); |
| | 16 | |
|
| | 17 | | private void Awake() => |
| 65 | 18 | | button = GetComponent<Button>(); |
| | 19 | |
|
| | 20 | | private void OnEnable() |
| | 21 | | { |
| 82 | 22 | | cts?.Cancel(); |
| 82 | 23 | | cts?.Dispose(); |
| 82 | 24 | | cts = new CancellationTokenSource(); |
| 82 | 25 | | DetectClicks().Forget(); |
| 82 | 26 | | } |
| | 27 | |
|
| | 28 | | private void OnDisable() |
| | 29 | | { |
| 82 | 30 | | cts?.Cancel(); |
| 82 | 31 | | cts?.Dispose(); |
| 82 | 32 | | cts = null; |
| 82 | 33 | | } |
| | 34 | |
|
| | 35 | | private async UniTaskVoid DetectClicks() |
| | 36 | | { |
| | 37 | | const int TIME_BETWEEN_CLICKS_MS = 200; |
| 82 | 38 | | TimeoutController timeoutController = new TimeoutController(cts); |
| 82 | 39 | | IAsyncClickEventHandler clickEventHandler = button.GetAsyncClickEventHandler(cts.Token); |
| 0 | 40 | | while (true) |
| | 41 | | { |
| 255 | 42 | | await clickEventHandler.OnClickAsync(); |
| | 43 | |
|
| 3 | 44 | | if(AlwaysPerformSingleClick) |
| 3 | 45 | | OnClick?.Invoke(); |
| | 46 | |
|
| 3 | 47 | | timeoutController.Reset(); |
| | 48 | |
|
| | 49 | | try |
| | 50 | | { |
| 9 | 51 | | await clickEventHandler.OnClickAsync().AttachExternalCancellation(timeoutController.Timeout(TIME_BETWEEN |
| 0 | 52 | | } |
| 3 | 53 | | catch (OperationCanceledException e) |
| | 54 | | { |
| 3 | 55 | | if(cts.IsCancellationRequested) |
| 0 | 56 | | throw; |
| 3 | 57 | | } |
| 3 | 58 | | if (timeoutController.IsTimeout()) |
| | 59 | | { |
| 3 | 60 | | OnClick?.Invoke(); |
| 3 | 61 | | continue; |
| | 62 | | } |
| 0 | 63 | | OnDoubleClick?.Invoke(); |
| | 64 | | } |
| | 65 | | } |
| | 66 | | } |