Unity實現倒計時組件
更新時間:2020年05月28日 15:00:36 作者:魔小明
這篇文章主要介紹了Unity實現倒計時組件的使用方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
前言
倒計時功能在游戲中一直很重要, 不管是活動開放時間,還是技能冷卻。
本文實現了一個通用倒計時組件,實現了倒計時的基本功能,支持倒計時結束后的回調。
設計思路
1、倒計時的實現是通過協(xié)程,WaitForSeconds(delay)可以很好的每隔一個delay執(zhí)行一次方法,如果需要很精細的時間, 可以將delay設置成0.1等小于1的值。
2、回調是在倒計時為0時,執(zhí)行一個Action類型的方法。
3、我的這個組件默認是需要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!!!"; } }
如有錯誤,歡迎指出。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。