using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
/// <summary>
/// 倒计时
/// </summary>
public class CountDownTimer : MonoBehaviour
{
// 需求: 1秒修改1次Text文本内容
// 1 查找组件引用
// 2 定义变量 秒
// 3 120 -> 02.00 119 -> 01.59
// 4 修改文本
private Text txtTimer;
public int second = 120;
private void Start()
{
txtTimer = this.GetComponent<Text>();
// 重复调用(函数名,第一次执行时间,每次执行间隔)
//InvokeRepeating("Timer2", 1, 1);
// 延迟执行
//Invoke(被执行的方法,开始调用时间);
}
private void Update()
{
Timer();
//Timer1();
}
// 方法一
// update 立即执行
private float nextTime = 1; //下次修改的时间
private void Timer()
{
if (Time.time >= nextTime)
{
second--;
txtTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
// 设置下次修改的时间
nextTime += 1;
if (second <= 10)
{
txtTimer.color = Color.red;
}
}
}
// 方法二
// update 隔时间执行
private float totalTime = 0;
private void Timer1()
{
totalTime += Time.deltaTime;
if(totalTime >= 1)
{
second--;
txtTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
totalTime = 0;
}
}
// 方法三
// start
// 每搁固定时间
private void Timer2()
{
second--;
txtTimer.text = string.Format("{0:d2}:{1:d1}", second / 60, second % 60);
if (second <= 0)
{
CancelInvoke("Timer");
}
}
// 5 如何让每秒修改一次
// 重点:在Update每帧执行的方法中,个别语句实现指定间隔执行一次
}
仅供个人学习
|