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、商城、支付、游戏、区块链、直播、影音、小说等源码教程,注册会员可免费学习交流。
用户必须遵守《计算机软件保护条例(2013修订)》第十七条:为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。鉴于此条例,用户从本平台下载的全部源码(软件)教程仅限学习研究,未经版权归属者授权不得商用,若因商用引起的版权纠纷,一切责任均由使用者自行承担,本平台所属公司及其雇员不承担任何法律责任。
暗黑源码库 » Unity3D之使用协程实现倒计时
赞助VIP 享更多特权,立即登录下载海量资源
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡