using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timert : MonoBehaviour
{
public int second = 120;
private Text txtTimer;
private float nextTime = 1;//下一次改变时间
// Start is called before the first frame update
void Start()
{
txtTimer = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
Timer1();
}
private void Timer1()
{
//如果时间到了
if (nextTime <= Time.time)
{
second--;//119 1:59
txtTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
nextTime = Time.time + 1;//在当前时间上增加1s
if (second <= 10) txtTimer.color = Color.red;
if (second <= 0) enabled = false;
}
}
}
using UnityEngine;
using UnityEngine.UI;
public class Timert : MonoBehaviour
{
public int second = 120;
private Text txtTimer;
private float totalTime=0;//下一次改变时间
// Start is called before the first frame update
void Start()
{
txtTimer = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
Timer2();
}
private void Timer2()
{
//累加每帧消耗时间
totalTime += Time.deltaTime;
//如果1s
if (totalTime >= 1)
{
second--;//119 1:59
txtTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
totalTime = 0;//清空累加的时间
if (second <= 10) txtTimer.color = Color.red;
if (second <= 0) enabled = false;
}
}
}
using UnityEngine;
using UnityEngine.UI;
public class Timert : MonoBehaviour
{
public int second = 120;
private Text txtTimer;
// Start is called before the first frame update
void Start()
{
txtTimer = GetComponent<Text>();
//重复调用(要执行的方法名称,开始调用时间,调用间隔)
InvokeRepeating("Timer", 0, 1);
//延迟调用
//Invoke("需要调用的方法名称", 调用时间);
}
private void Timer()
{
second--;//119 1:59
txtTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
if (second <= 10) txtTimer.color = Color.red;
// 取消调用
if (second <= 0) {CancelInvoke("Timer");}
}
}