SimpleTimer.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | using System.Collections; using UnityEngine; using UnityEngine.UI; public class SimpleTimer : MonoBehaviour { public Text timerTxt; public Button startTimerBtn; public Button stopTimerBtn; IEnumerator _timerCR; void Awake() { startTimerBtn.onClick.AddListener(StartTimerClick); stopTimerBtn.onClick.AddListener(StopTimerClick); ResetTimer(); } #region button clicks void StartTimerClick() { _timerCR = StartTimer(); StartCoroutine(_timerCR); } void StopTimerClick() { if (_timerCR!= null ) { StopCoroutine(_timerCR); _timerCR = null ; } ResetTimer(); } #endregion #region start/reset timer IEnumerator StartTimer( int timeRemaining = 10) { startTimerBtn.interactable = false ; stopTimerBtn.interactable = true ; for ( int i = timeRemaining; i > 0; i--) { timerTxt.text = i.ToString( "00" ); yield return new WaitForSeconds(1); } ResetTimer(); } void ResetTimer() { startTimerBtn.interactable = true ; stopTimerBtn.interactable = false ; timerTxt.text = "00" ; } #endregion } |