// 定义定时器容器 Dictionary<string, WaitForSecondsRealtime> RealtimeDict = new Dictionary<string, WaitForSecondsRealtime>(); // 剩余时长 private float timeRemaining; // 开始计时 public void StartTimer(float duration) { timeRemaining = duration; RealtimeDict.Add("Realtime", new WaitForSecondsRealtime(timeRemaining)); StartCoroutine(TrackTimeCoroutine()); } // 跟踪时间的协程 private IEnumerator TrackTimeCoroutine() { while (timeRemaining > 0) { // 等待一段实时时间 WaitForSecondsRealtime timer = RealtimeDict["Realtime"]; yield return timer; timeRemaining = 0; Debug.Log("定时器完成代码逻辑"); } } // 更新time public void UpdateTime() { WaitForSecondsRealtime timer = RealtimeDict["Realtime"]; if(timer != null){ timer.Reset(); } } // 获取剩余时长 public float GetTimeRemaining() { return timeRemaining; }
改良后:
float currentTime=0; // 剩余时长 private float timeRemaining=0; // 开始计时 public void StartTimer(float duration) { timeRemaining = duration; StartCoroutine(TrackTimeCoroutine()); } // 跟踪时间的协程 private IEnumerator TrackTimeCoroutine() { while (timeRemaining > 0) { // 等待一段实时时间 WaitForSecondsRealtime timer = new WaitForSecondsRealtime(1); yield return timer; timeRemaining -= 1; Debug.LogWarning("定时器完成代码逻辑:GetTimeRemaining:" + GetTimeRemaining()); } Debug.LogWarning("定时器完成代码逻辑:GetTimeRemaining:" + GetTimeRemaining()); } // 获取剩余时长 public float GetTimeRemaining() { return timeRemaining; }
标签:timeRemaining,float,开启,timer,unity,计时器,WaitForSecondsRealtime,GetTimeRemaining,p From: https://www.cnblogs.com/WalkingSnail/p/18172164