using System.Collections; using UnityEngine; using UnityEngine.Events; public class TimeCounterManager : MonoBehaviour { public int countDown; int time = 0; string time_FormatStr = "00:00:00"; Coroutine timeCounterCoroutine; public void Init() { ClearTimeCounter(); } public void StartTimeCounter(UnityAction callBack=null) { if (timeCounterCoroutine == null) { timeCounterCoroutine = StartCoroutine(TimeCounter(callBack)); } } public void StopTimeCounter() { if (timeCounterCoroutine != null) { StopCoroutine(timeCounterCoroutine); timeCounterCoroutine = null; } } public void ClearTimeCounter() { time = countDown; time_FormatStr = string.Format("{0:d2}:{1:d2}:{2:d2}", time / 3600, time % 3600 / 60, time % 3600 % 60); } public string GetTimeStr() { return time_FormatStr; } public int GetTimeInt() { return time; } public string GetRemainTime() { return string.Format("{0:d2}:{1:d2}:{2:d2}", (countDown - time) / 3600, (countDown - time) % 3600 / 60, (countDown - time) % 3600 % 60); ; } IEnumerator TimeCounter(UnityAction callBack) { while (true) { yield return new WaitForSeconds(1f); if (countDown == 0) { time++; } else { time--; } time_FormatStr = string.Format("{0:d2}:{1:d2}:{2:d2}", time / 3600, time % 3600 / 60, time % 3600 % 60); callBack?.Invoke(string.Format("{0:d2}:{1:d2}:{2:d2}", time / 3600, time % 3600 / 60, time % 3600 % 60)); if(time <= 0) { yield break; } } } }