Unity實現(xiàn)倒計時組件
前言
倒計時功能在游戲中一直很重要, 不管是活動開放時間,還是技能冷卻。
本文實現(xiàn)了一個通用倒計時組件,實現(xiàn)了倒計時的基本功能,支持倒計時結(jié)束后的回調(diào)。
設(shè)計思路
1、倒計時的實現(xiàn)是通過協(xié)程,WaitForSeconds(delay)可以很好的每隔一個delay執(zhí)行一次方法,如果需要很精細的時間, 可以將delay設(shè)置成0.1等小于1的值。
2、回調(diào)是在倒計時為0時,執(zhí)行一個Action類型的方法。
3、我的這個組件默認是需要Text組件來顯示, 也可以根據(jù)需求刪除。
先看效果:

代碼實現(xiàn)
// 倒計時
// 倒計時結(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!!!";
}
}
如有錯誤,歡迎指出。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在C#使用字典存儲事件示例及實現(xiàn)自定義事件訪問器
這篇文章主要介紹了在C#使用字典存儲事件示例及實現(xiàn)自定義事件訪問器的方法,是C#事件編程中的基礎(chǔ)知識,需要的朋友可以參考下2016-02-02
WPF運行時替換方法實現(xiàn)mvvm自動觸發(fā)刷新
這篇文章主要為大家詳細介紹了WPF運行時如何實現(xiàn)setter不需要調(diào)方法就可以自動觸發(fā)界面刷新,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04

