这篇文章主要介绍了Unity实现倒计时组件的使用方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
前言
倒计时功能在游戏中一直很重要, 不管是活动开放时间,还是技能冷却。
本文实现了一个通用倒计时组件,实现了倒计时的基本功能,支持倒计时结束后的回调。
设计思路
1、倒计时的实现是通过协程,WaitForSeconds(delay)可以很好的每隔一个delay执行一次方法,如果需要很精细的时间, 可以将delay设置成0.1等小于1的值。
2、回调是在倒计时为0时,执行一个Action类型的方法。
3、我的这个组件默认是需要Text组件来显示, 也可以根据需求删除。
先看效果:
代码实现
// 倒计时
// 倒计时结束的回调
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实现倒计时组件


基础教程推荐
猜你喜欢
- C#中 Json 序列化去掉null值的方法 2022-11-18
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- Unity shader实现高斯模糊效果 2023-01-16
- 实例详解C#实现http不同方法的请求 2022-12-26
- C# 解析XML和反序列化的示例 2023-04-14
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#中的Linq to JSON操作详解 2023-06-08