Unity3D之使用协程实现倒计时

一, 场景设置 二, 脚本 Ⅰ, 封装协程倒计时类(相当于工具) XCTime.as using System; using System.Collections; using System.Collections.Generic; using UnityEngine; ///

/// 提供了协程实现的倒计时封装 ///

public class XCTime : MonoBehaviour { ///

/// 回调函数 ///

private Action callback; ///

/// 总的CD ///

private int totalSeconds; ///

/// 剩余的CD ///

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();//更新数据 } } 三, 挂载脚本

尚美源码坑位教程提供精美的网站源码教程,小程序、公众号、H5、APP、游戏、直播、支付、区块链、商城、影音、小说等源码信息大全。
尚美源码教程库 » Unity3D之使用协程实现倒计时
赞助VIP 享更多特权,立即登录下载海量资源
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡