//显示时间
public static void UpdataTime (float time)
{
int minute = (int)(time / 60);
int seconds = (int)(time % 60);
instence.timeText.text = minute.ToString("00") + ":" + seconds.ToString("00");
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
///
/// 倒计时
///
public class CountdownTimer : MonoBehaviour
{
//需求:1秒修改1次Text文本内容
//1.查找组件引用
//2.定义变量秒second
//3.120 --> 02:00
//4.修改文本
private Text textTimer;
public int second = 120;
private void Start()
{
textTimer = GetComponent<Text>();
//Time3
//重复调用(被执行的方法名称,第一次执行时机,每次执行间隔)
InvokeRepeating("Timer3", 1, 1);
//invoke(被执行的方法,开始调用时机);
}
private void Update()
{
//Timer2();
}
private float nextTime = 1;//下次修改时间
//方法1:Time.time
//先做 再等
private void Timer1()
{
//如果到了修改时间
if (Time.time > nextTime)
{
second--;
textTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
if (second <= 10)
{
this.textTimer.color = Color.red;
}
//设置下次修改时间
nextTime = Time.time + 1;
}
}
private float totalTime;
//方法2:Time.deltatime
//先等 再做
private void Timer2()
{
//累加每帧间隔
totalTime += Time.deltaTime;
if (totalTime >= 1)
{
second--;
textTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
if (second <= 10)
{
this.textTimer.color = Color.red;
}
totalTime = 0;
}
}
//方法3:invoke()
//每隔固定时间,重复执行
private void Timer3()
{
second--;
textTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
if (second <= 10)
{
this.textTimer.color = Color.red;
}
if (second <=0)
{
//print("stop");
CancelInvoke("Timer3" );//取消方法调用
}
}
//5.如何一秒修改一次
//重点:在Updata每帧执行的方法中,个别语句实现制定间隔执行一次
}