在 Unity 中实现倒计时功能,主要基于对时间的精确计算和监控,根据不同的应用场景和需求,可以采用不同的实现方式,以下详细介绍常见的实现原理及示例:
基于 Time.deltaTime 实现倒计时
原理
Time.deltaTime 是 Unity 中的一个内置属性,它代表从上一帧到当前帧所经过的时间(以秒为单位)。利用这个属性,在每一帧中从预设的倒计时总时长里减去 Time.deltaTime,持续更新剩余时间,直到倒计时结束。
里面也是两种方法实现
具体实现代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 倒计时的实现
/// </summary>
public class CountDownTime : MonoBehaviour
{
private Text text;
int Shi;
int Fen;
int miao;
private bool aa;
public float time;
// Start is called before the first frame update
void Start()
{
text = this.GetComponent<Text>();
StartCoroutine("enumerator");
//Endkisijd();
}
public void Endkisijd()
{
aa = true;
}
#region 第一种方法
IEnumerator enumerator()
{
while (time >= 0)
{
Shi = (int)time / 3600;
Fen = (int)time % 3600 / 60;
miao = (int)time % 60;
text.text = string.Format ("{0}:{1}:{2}",Shi,Fen ,miao );
yield return new WaitForSeconds(1);
time--;
}
}
#endregion
// Update is called once per frame
void Update()
{
#region 第二种方法
/*
if (aa)
{
Shi = (int)time / 3600;
Fen = (int)time % 3600 / 60;
miao = (int)time % 60;
text.text = string.Format("{0}:{1}:{2}", Shi, Fen, miao);
}
if (time > 0)
{
time -= Time.deltaTime;
}
else
{
text.text = string.Format("{0}:{1}:{2}", 00, 00, 00);
aa = false;
}
*/
#endregion
}
}
记得创建一个text组件挂载到上面,要不然报错