using System; using System.Collections.Concurrent; using System.Threading; using UnityEngine; using UnityEngine.UI; using ZGameFramework; namespace Script.UI { public class CountDownItem : MonoBehaviour { public Text text; public Text title; public int minute; private Timer _timer; private bool isCountDown; private ConcurrentQueue _queue = new ConcurrentQueue(); private double _time; private void OnEnable() { title.text = FileManager.Instance.GetTitle.title; _time = 0; StartCountDown(minute); } private void StartCountDown(double time) { isCountDown = true; _timer = new Timer(Callback, null, TimeSpan.FromSeconds(time), Timeout.InfiniteTimeSpan); } private void Callback(object o) { isCountDown = false; _queue.Enqueue(() => { OnEnd(); text.text = "00:00:00"; }); } public void Pause() { isCountDown = false; _timer.Dispose(); } public void Resume() { StartCountDown(minute - _time); } private void OnEnd() { Debug.Log("倒计时结束"); var fromSeconds = TimeSpan.FromSeconds(_time); var time = fromSeconds.ToCustomString(); GlobalManager.Instance.SetTime(time); var panelBase = UIManager.Instance.GetPanel(PanelType.Answering); var answeringPanel = panelBase as AnsweringPanel; answeringPanel.SaveData(); UIManager.Instance.OpenPanel(PanelType.Summary); } private void Update() { while (_queue.TryDequeue(out var action)) { action?.Invoke(); } if (isCountDown) { _time += Time.deltaTime; //剩余的时间 var remainTime = TimeSpan.FromSeconds(minute) - TimeSpan.FromSeconds(_time); text.text = remainTime.ToCustomString(); } } private void OnDisable() { _timer.Dispose(); } public void StopCountDown() { _timer.Dispose(); isCountDown = false; var fromSeconds = TimeSpan.FromSeconds(_time); var time = fromSeconds.ToCustomString(); GlobalManager.Instance.SetTime(time); } } } public static class TimeSpanUtil { public static string ToCustomString(this TimeSpan timeSpan) { return timeSpan.ToString(@"hh\:mm\:ss"); } }