Unity實(shí)現(xiàn)倒計(jì)時(shí)組件
前言
倒計(jì)時(shí)功能在游戲中一直很重要, 不管是活動(dòng)開放時(shí)間,還是技能冷卻。
本文實(shí)現(xiàn)了一個(gè)通用倒計(jì)時(shí)組件,實(shí)現(xiàn)了倒計(jì)時(shí)的基本功能,支持倒計(jì)時(shí)結(jié)束后的回調(diào)。
設(shè)計(jì)思路
1、倒計(jì)時(shí)的實(shí)現(xiàn)是通過協(xié)程,WaitForSeconds(delay)可以很好的每隔一個(gè)delay執(zhí)行一次方法,如果需要很精細(xì)的時(shí)間, 可以將delay設(shè)置成0.1等小于1的值。
2、回調(diào)是在倒計(jì)時(shí)為0時(shí),執(zhí)行一個(gè)Action類型的方法。
3、我的這個(gè)組件默認(rèn)是需要Text組件來顯示, 也可以根據(jù)需求刪除。
先看效果:
代碼實(shí)現(xiàn)
// 倒計(jì)時(shí) // 倒計(jì)時(shí)結(jié)束的回調(diào) 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!!!"; } }
如有錯(cuò)誤,歡迎指出。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實(shí)現(xiàn)獲取運(yùn)行平臺(tái)系統(tǒng)信息的方法
這篇文章主要介紹了C#實(shí)現(xiàn)獲取運(yùn)行平臺(tái)系統(tǒng)信息的方法,比較典型的C#應(yīng)用,需要的朋友可以參考下2014-07-07C#實(shí)現(xiàn)windows form倒計(jì)時(shí)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)windows form倒計(jì)時(shí)的方法,涉及C#桌面程序設(shè)計(jì)中時(shí)間操作的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04C#中使用1.7版本驅(qū)動(dòng)操作MongoDB簡(jiǎn)單例子
這篇文章主要介紹了C#中使用1.7版本驅(qū)動(dòng)操作MongoDB簡(jiǎn)單例子,本文給出了連接MongoDB、操作MongoDB數(shù)據(jù)等例子,需要的朋友可以參考下2015-01-01C#實(shí)現(xiàn)將CSV轉(zhuǎn)為XLSX文件
Microsoft?Excel的XLSX格式以及基于文本的CSV(逗號(hào)分隔值)格式,是數(shù)據(jù)交換中常見的文件格式,本文主要介紹了如何在C#中以編程的方式將CSV文件轉(zhuǎn)化為XLSX?文件,需要的可以參考下2024-03-03在C#使用字典存儲(chǔ)事件示例及實(shí)現(xiàn)自定義事件訪問器
這篇文章主要介紹了在C#使用字典存儲(chǔ)事件示例及實(shí)現(xiàn)自定義事件訪問器的方法,是C#事件編程中的基礎(chǔ)知識(shí),需要的朋友可以參考下2016-02-02WPF運(yùn)行時(shí)替換方法實(shí)現(xiàn)mvvm自動(dòng)觸發(fā)刷新
這篇文章主要為大家詳細(xì)介紹了WPF運(yùn)行時(shí)如何實(shí)現(xiàn)setter不需要調(diào)方法就可以自動(dòng)觸發(fā)界面刷新,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04