c# - 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
}
}
}
解决方案
FixedUpdate
实际上只用于物理,你不应该改变你想做的事情的间隔......
宁可使用Update
,Time.deltaTime
如果可能的话。即使在FixedUpdate
它推荐使用Time.deltaTime
(见Time.fixedDeltaTime
)
但是,在您的情况下,为了以精确的时间步长递增,您可能会考虑使用(或可能)类似的协程WaitForSeconds
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##");
}
}
推荐阅读
- mysql - mysql 和 mysql2 在 Fission 运行时中不起作用
- bash - Macos中保存的终端导出变量在哪里
- mysql - MySQL / MariaDB - 从数据库中删除除最后一条记录外的所有记录
- java - 如何使用卡片视图将数据从一项活动传输到另一项活动?
- nginx - Nginx缓存第一个浏览器请求总是Miss
- c++ - 这段代码是如何工作的?关于指针,字符串文字
- yaml - GCP/GKE 添加网络标签
- javascript - 按字符对字符串数组进行排序并返回所有匹配的元素
- c - 混合 c 和组装 cortex-m0
- python - 销毁 tkinter 标签