温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解Unity如何实现倒计时组件

发布时间:2020-07-21 09:54:02 来源:亿速云 阅读:221 作者:小猪 栏目:编程语言

小编这次要给大家分享的是详解Unity如何实现倒计时组件,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

前言

倒计时功能在游戏中一直很重要, 不管是活动开放时间,还是技能冷却。
本文实现了一个通用倒计时组件,实现了倒计时的基本功能,支持倒计时结束后的回调。

设计思路

1、倒计时的实现是通过协程,WaitForSeconds(delay)可以很好的每隔一个delay执行一次方法,如果需要很精细的时间, 可以将delay设置成0.1等小于1的值。
2、回调是在倒计时为0时,执行一个Action类型的方法。
3、我的这个组件默认是需要Text组件来显示, 也可以根据需求删除。

先看效果:

详解Unity如何实现倒计时组件

代码实现

// 倒计时
// 倒计时结束的回调

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!!!";
  }
}

看完这篇关于详解Unity如何实现倒计时组件的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI