1- using System . Collections ;
1+ using System . Threading ;
22using UnityEngine ;
33using UnityEngine . EventSystems ;
44using UnityEngine . UI ;
5+ using Cysharp . Threading . Tasks ;
56
67namespace Code . UI
78{
89 public class ButtonScaler : MonoBehaviour , IPointerDownHandler , IPointerUpHandler
910 {
1011 [ SerializeField ] private Image _image ;
12+
1113 [ Header ( "Setup" ) ]
1214 [ SerializeField ] private float ScaleAmount = 0.8f ;
1315 [ SerializeField ] private float ScaleDuration = 0.2f ;
14-
16+
1517 private Vector3 _originalScale ;
16-
18+ private CancellationTokenSource _scaleCts ;
19+
1720 private void Start ( ) => SetupScaleOrigin ( ) ;
1821
1922 public void SetupScaleOrigin ( )
@@ -23,39 +26,41 @@ public void SetupScaleOrigin()
2326
2427 public void OnPointerDown ( PointerEventData eventData )
2528 {
26- StopAllCoroutines ( ) ;
27- _image . transform . localScale = _originalScale ;
28-
2929 if ( ! _image . gameObject . activeInHierarchy )
3030 return ;
31-
32- StartCoroutine ( ScaleButton ( _originalScale * ScaleAmount , ScaleDuration ) ) ;
31+
32+ _scaleCts ? . Cancel ( ) ;
33+ _scaleCts = new CancellationTokenSource ( ) ;
34+ _ = ScaleButtonAsync ( _originalScale * ScaleAmount , ScaleDuration , _scaleCts . Token ) ;
3335 }
3436
3537 public void OnPointerUp ( PointerEventData eventData )
3638 {
37- StopAllCoroutines ( ) ;
38-
3939 if ( ! _image . gameObject . activeInHierarchy )
4040 return ;
4141
42- StartCoroutine ( ScaleButton ( _originalScale , ScaleDuration ) ) ;
42+ _scaleCts ? . Cancel ( ) ;
43+ _scaleCts = new CancellationTokenSource ( ) ;
44+ _ = ScaleButtonAsync ( _originalScale , ScaleDuration , _scaleCts . Token ) ;
4345 }
4446
45- private IEnumerator ScaleButton ( Vector3 targetScale , float duration )
47+ private async UniTaskVoid ScaleButtonAsync ( Vector3 targetScale , float duration , CancellationToken token )
4648 {
47- float time = 0 ;
49+ float time = 0f ;
4850 Vector3 startScale = _image . transform . localScale ;
4951
5052 while ( time < duration )
5153 {
54+ if ( token . IsCancellationRequested )
55+ return ;
56+
5257 float t = time / duration ;
5358 _image . transform . localScale = Vector3 . Lerp ( startScale , targetScale , t ) ;
5459 time += Time . unscaledDeltaTime ;
55- yield return null ;
60+ await UniTask . Yield ( PlayerLoopTiming . Update , token ) ;
5661 }
5762
5863 _image . transform . localScale = targetScale ;
5964 }
60- }
61- }
65+ }
66+ }
0 commit comments