Unity内实现倒计时组件
来源:互联网 发布:河南网络电视公益活动 编辑:程序博客网 时间:2024/05/29 08:35
前言
倒计时功能在游戏中一直很重要, 不管是活动开放时间,还是技能冷却。
本文实现了一个通用倒计时组件,实现了倒计时的基本功能,支持倒计时结束后的回调。
设计思路
- 倒计时的实现是通过协程,WaitForSeconds(delay)可以很好的每隔一个delay执行一次方法,如果需要很精细的时间, 可以将delay设置成0.1等小于1的值。
- 回调是在倒计时为0时,执行一个Action类型的方法。
- 我的这个组件默认是需要Text组件来显示, 也可以根据需求删除。
先看效果:
代码实现
// 倒计时// 倒计时结束的回调using System;using System.Collections;using UnityEngine;using UnityEngine.UI;[RequireComponent(typeof(Text))]public class CountDownTime : MonoBehaviour{ public int testTime = 15; private int _timeLeft = 0; private Text _textTimer = null; private float _delay = 1; private Action _endCallback = null; private void Start() { if (_textTimer == null) _textTimer = GetComponent<Text>(); SetEndCallback(TestEndCallback); Begin(testTime, true); } public void SetEndCallback(Action callback) { _endCallback = callback; } public void Begin(int timeLeft, bool isRightNow) { _timeLeft = timeLeft; if (_textTimer == null) _textTimer = GetComponent<Text>(); if (isRightNow) CountDown(); if (gameObject.activeInHierarchy) StartCoroutine(Polling(_delay, CountDown)); } private IEnumerator Polling(float delay, Action voidFunc) { while (delay > 0) { voidFunc(); if (_timeLeft < 0 && _endCallback != null) { _endCallback(); _endCallback = null; yield return null; } yield return new WaitForSeconds(delay); } } private void CountDown() { if (_timeLeft >= 0) { TimeSpan ts = new TimeSpan(0, 0, _timeLeft--); _textTimer.text = ts.ToString(); } else if (_timeLeft < -1) { _textTimer.text = _timeLeft.ToString(); } } private void TestEndCallback() { _textTimer.text = "End!!!"; }}
如有错误,欢迎指出。
email:dxmdxm1992#gmail.com
blog: http://blog.csdn.net/david_dai_1108
阅读全文
0 0
- Unity内实现倒计时组件
- Unity 倒计时简单实现
- Unity 实现倒计时 协程
- Unity 3d 实现倒计时
- unity倒计时
- unity游戏开发----unity中自定义比分倒计时实现
- 倒计时组件
- Unity内部类实现GPS定位
- unity 携程倒计时
- Unity倒计时动画
- Unity游戏开发倒计时
- Unity之图片轮播组件实现
- JS倒计时组件
- Actionscript 倒计时组件
- JavaScript倒计时组件
- RN自定义倒计时组件
- angular2 倒计时组件
- Angular2 倒计时组件
- maven的setting配置位置
- [bzoj4813][树形dp]小Q的棋盘
- centos7 上不去网解决办法
- 转发和重定向的区别
- 周易六十四卦——水风井卦
- Unity内实现倒计时组件
- android的WebView遇到的
- DesignBuilder自定义材料文件
- B和B+树
- 关于线程暂停或指示线程准备暂停的十种方式介绍
- 通达oa破解版/通达oa破解版下载/通达oa2017破解版
- php 字符串处理函数
- 分布式环境之-zookeeper
- #2016京东实习生笔试之生日礼物