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

提供优质的网站源码大全,小程序、APP、H5、支付、游戏、区块链、商城、直播、影音、小说、公众号等源码下载。
易搜网络技术公司 » Unity3D之使用协程实现倒计时
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡