最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

前言

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

最新評論

阳新县| 留坝县| 岚皋县| 石棉县| 苗栗县| 平和县| 涡阳县| 万荣县| 台山市| 北流市| 富宁县| 霸州市| 海伦市| 玉龙| 苏州市| 石家庄市| 丽江市| 永平县| 资源县| 永德县| 常熟市| 合山市| 会同县| 固始县| 延津县| 福建省| 巴林左旗| 黑龙江省| 高清| 远安县| 西青区| 莱芜市| 凤阳县| 卓尼县| 集贤县| 离岛区| 沙坪坝区| 商丘市| 沂源县| 化隆| 广汉市|