首页 > 解决方案 > Unity 中的计时器增量不正确

问题描述

我有下面的代码,用于 Unity 中的简单计时器 UI。我试图强制计时器以 0.01 秒的增量精确更新,然后在 8 秒时重置。播放脚本时,我看到计时器增加了 0.011 秒。在统一本身中,我设置了 Fixed Timestep = 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
        }

    }
}

标签: c#unity3d

解决方案


FixedUpdate实际上只用于物理,你不应该改变你想做的事情的间隔......

宁可使用UpdateTime.deltaTime如果可能的话。即使在FixedUpdate它推荐使用Time.deltaTime(见Time.fixedDeltaTime


但是,在您的情况下,为了以精确的时间步长递增,您可能会考虑使用(或可能)类似的协程WaitForSecondsWaitForSecondsRealtime

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##");
    }
}

在此处输入图像描述


推荐阅读