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

代碼實(shí)現(xiàn)
// 倒計(jì)時
// 倒計(jì)時結(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# 4.0 大數(shù)的運(yùn)算--BigInteger的應(yīng)用詳解
本篇文章是對C# 4.0 大數(shù)的運(yùn)算 BigInteger的應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C#使用post發(fā)送和接收數(shù)據(jù)的方法
這篇文章主要介紹了C#使用post發(fā)送和接收數(shù)據(jù)的方法,涉及C#使用post收發(fā)數(shù)據(jù)的相關(guān)技巧,非常具有實(shí)用價值,需要的朋友可以參考下2015-04-04
C#結(jié)合JavaScript實(shí)現(xiàn)多文件上傳功能
在許多應(yīng)用場景里,多文件上傳是一項(xiàng)比較實(shí)用的功能,本文主要為大家詳細(xì)介紹了C#如何結(jié)合JavaScript實(shí)現(xiàn)多文件上傳功能,感興趣的小伙伴可以了解下2023-12-12
詳解WPF雙滑塊控件的使用和強(qiáng)制捕獲鼠標(biāo)事件焦點(diǎn)
這篇文章主要為大家詳細(xì)介紹了WPF中雙滑塊控件的使用和強(qiáng)制捕獲鼠標(biāo)事件焦點(diǎn)的實(shí)現(xiàn),文中的示例代碼講解詳細(xì),感興趣的可以嘗試一下2022-07-07

