using Cysharp.Threading.Tasks; using Gameplay; using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; public class TimerText : MonoBehaviour { private Timer timer; private TMPro.TextMeshProUGUI text; public void SetTimer(float time) { if (timer == null) { timer = new Timer(); text = GetComponent(); } timer.SetTimer(time); } public void StartTimer() { timer.StartTimer(); timer.OnValueChanged += OnValueChange; } public void StopTimer() { timer.StopTimer(); timer.OnValueChanged -= OnValueChange; } void OnValueChange(float time) { TimeSpan remains = TimeSpan.FromSeconds(time); var day = remains.Days; var hour = remains.Hours; var minute = remains.Minutes; var second = remains.Seconds; StringBuilder sb = new StringBuilder(); sb.Append(CommonUtils.GetLocalizeText("Ê£Óà")); if (day > 0) sb.Append($"{day}d {hour:D2}h"); else if (hour > 0) sb.Append($"{hour:D2}h {minute:D2}m {second:D2}s"); else if (minute > 0) sb.Append($"{minute:D2}m {second:D2}s"); else sb.Append($"{second:D2}s"); text.text = sb.ToString(); } } public class Timer { private float RemainingTime; private bool IsRunning; public delegate void OnValueChange(float time); public event OnValueChange OnValueChanged; public delegate void OnTimerEnd(); public event OnTimerEnd OnTimerEndEvent; public void SetTimer(float time) { RemainingTime = time; } public void StartTimer() { if (IsRunning) return; IsRunning = true; CoreTimer(); } public void StopTimer() { IsRunning = false; } async void CoreTimer() { while (IsRunning) { await UniTask.Delay(1000); RemainingTime--; OnValueChanged?.Invoke(RemainingTime); if (RemainingTime <= 0) { StopTimer(); OnTimerEndEvent?.Invoke(); } } } }