倒计时实现—三种方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CountdownDemo : MonoBehaviour
{
//需求1秒修改一次Text的内容
//倒计时为10秒时text变红
private Text texttimer;
public int second = 120;//second为int类型
private float nextTime = 1f;
private float totalTime = 0;//累计时间
private void Start()
{
texttimer = this.GetComponent<Text>();
//*方法3
//重复调用(被执行的方法名称,第一次执行的时间,每次执行间隔)
InvokeRepeating("Countdown1",1,1);
//Invoke(被执行的方法,开始调用的时间);
}
private void Update()
{
//*方法1
//Countdown1();
//*方法2
//Countdown2();
}
/// <summary>
/// 方法1:Time.time
/// </summary>
public void Countdown1()
{
//C 货币 string.Format("{0:C3}", 2) $2.000
//D 十进制 string.Format("{0:D3}", 2) 002
//E 科学计数法 1.20E+001 1.20E+001
//G 常规 string.Format("{0:G}", 2) 2
//N 用分号隔开的数字 string.Format("{0:N}", 250000) 250,000.00
//X 十六进制 string.Format("{0:X000}", 12) C
// string.Format("{0:000.000}", 12.2) 012.200
//开始时Time.time为0,nexttime为1
if (Time.time >= nextTime)
{
second--;
texttimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
//小于10秒时变红
if (second <= 10)
{
texttimer.color = Color.red;
}
//设置下次修改时间
nextTime = Time.time + 1;
}
}
/// <summary>
/// 方法2:Time.deltaTime
/// </summary>
public void Countdown2()
{
//累加每帧间隔
totalTime += Time.deltaTime;
if (totalTime >= 1)
{
second--;
texttimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
if (second <= 10)
{
texttimer.color = Color.red;
}
totalTime = 0;
}
}
/// <summary>
/// 方法3:Invoke()
/// 每隔固定时间执行
/// </summary>
private void Countdown3()
{
second--;
texttimer.text = string.Format("{0:d2}:{0,d2}", second / 60, second % 60);
if (second <= 10)
{
texttimer.color = Color.red;
}
if (second<=0)
{
CancelInvoke("Countdown3");//取消调用
}
}
}
|