Unity中不正确的计时器增量

时间:2019-06-27 20:29:30

标签: c# unity3d

我有以下代码用于Unity中的简单计时器UI。我试图强制计时器精确地以0.01秒为增量进行更新,然后在8秒时重置。播放脚本时,我看到计时器增加了0.011秒。我已经统一设置了固定时间步长= 0.01。为什么会出错?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UI_Time : MonoBehaviour {

    public Text uiText;
    private int curStep = 0;
    private double timer = Variables.timer;


    // Trying fixed update as an attempted workaround
    void FixedUpdate()
    {
        timer += Time.fixedDeltaTime;

        if (timer > 8)
            {
                timer = 0d;
            }
        else
        {
            uiText.text = "Time: " + timer.ToString(".0##");  //Set the text field
        }

    }
}

1 个答案:

答案 0 :(得分:3)

FixedUpdate实际上仅用于物理,您不应更改其间隔以进行操作...

尽可能使用UpdateTime.deltaTime。即使在FixedUpdate中,也建议使用Time.deltaTime(请参见Time.fixedDeltaTime


但是,对于您来说,要在确切的时间步长上递增,您可以考虑将CoroutineWaitForSeconds(或者也许是WaitForSecondsRealtime)一起使用

using System.Collections;

//...

private void Start()
{
    StartCoroutine(RunTimer());
}

private IEnumerator RunTimer()
{
    var time = 0f;
    uiText.text = "Time: " + time.ToString("#.0##");

    // looks scary but is okey in a coroutine as long as you yield somewhere inside
    while(true)
    {
        // yield return makes the routine pause here
        // allow Unity to render this frame
        // and continue from here in the next frame
        //
        // WaitForSeconds .. does what the name says
        yield return new WaitForSeconds(0.01f);

        time += 0.01f;
        uiText.text = "Time: " + time.ToString("#.0##");
    }
}

enter image description here