关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

Unity三种倒计时的方法

发布时间:2020-01-18 16:16:07

第一种,通过使用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()中)
private float totalTime;
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--;
    }


/template/Home/Zkeys/PC/Static