欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Unity實(shí)現(xiàn)倒計(jì)時(shí)組件

 更新時(shí)間:2020年05月28日 15:00:36   作者:魔小明  
這篇文章主要介紹了Unity實(shí)現(xiàn)倒計(jì)時(shí)組件的使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

前言

倒計(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)文章

最新評(píng)論