unity 10秒倒计时 使用Time.deltaTime,通过InvokeRepeating方法中

unity 10秒倒计时 使用Time.deltaTime,通过InvokeRepeating方法中

第一种是用Time.time(游戏已经玩完的时间)和时间间隔(1s)来判断。 (写在 Update() 中)


//倒计时开始的秒数
public int seconds=任意整数;
//间隔时间t
private float t=1;
public void Update()
{
Timer1();
}
public void Timer1()
    {
        if (Time.time >= t)//若写“==”将出现错误 有可能是1.00001s
        {
            seconds--;
            t += 1;
        }
    }

第二种,通过使用 Time.deltaTime(写在 Update() 中)

私人浮动总时间;

public void Update()
{
Timer2();
}
//累计每帧时间
public void Timer2()
{
totalTime += Time.deltaTime;
//和上次时间差1时执行
        if(totalTime>=1)
        {
            seconds--;
            totalTime=0;
        }
 }

三、通过InvokeRepeating方法(写在Start()中)

public void Start()
{
InvokeRepeating("Timer3", 0, 1);
}//调用Timer3方法 从0秒开始 间隔1秒
//。。。
public void Timer3()
    {
        txt.text = $"{seconds / 60:d2}:{seconds % 60:d2}";
        seconds--;
    }