一, 场景设置 二, 脚本 Ⅰ, 封装协程倒计时类(相当于工具) XCTime.as using System; using System.Collections; using System.Collections.Generic; using UnityEngine; ///
public class XCTime : MonoBehaviour { ///
private Action callback; ///
private int totalSeconds; ///
private int surplusSeconds; ///
private Boolean isNeedInited; ///
/// 回调函数 剩余秒数,总秒数 /// 总的秒数 /// 是否需要初始化(直接调用一次回调) public void StartCD( Action callback , int totalSeconds , Boolean isNeedInited = true ) { this.StopCD(); this.callback = callback; this.totalSeconds = totalSeconds; this.surplusSeconds = totalSeconds; this.isNeedInited = isNeedInited; if (this.totalSeconds <= 0) { if (this.isNeedInited) { this.callback(0, 0); } this.Clear(false); } else { if (this.isNeedInited) { this.callback(this.surplusSeconds, this.totalSeconds); } this.StartCoroutine(this.CountDown());//开启倒计时 } } ///
public void StopCD() { this.StopCoroutine(this.CountDown()); } ///
/// private IEnumerator CountDown() { while (true) { yield return new WaitForSeconds(1);//每一秒执行1次 this.surplusSeconds--; this.callback(this.surplusSeconds, this.totalSeconds); if (this.surplusSeconds <= 0) { this.Clear(true); break; } } } private void Clear( Boolean isNeedStop ) { if (isNeedStop) { this.StopCD(); } if (this.callback != null) { this.callback = null; } } public void OnDestroy() { this.Clear(true); } } Ⅱ, 使用工具的脚本 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; ///
[RequireComponent(typeof(XCTime))] public class CountDownDemo : MonoBehaviour { private XCTime cdHelper; private Text txtCD; // Start is called before the first frame update void Start() { this.cdHelper = this.gameObject.GetComponent(); this.txtCD = this.gameObject.transform.Find("TxtCD").GetComponent(); this.cdHelper.StartCD(this.ResetCD, 100, true);//开始倒计时 } private void ResetCD(int surplus, int total) { this.txtCD.text = surplus.ToString();//更新数据 } } 三, 挂载脚本