我只是用一个通用代码来统计玩家在更新函数中玩了多长时间:
float time;
void Update()
{
time += Time.unscaledDeltaTime;
}
问题是:
当我按下 Android 设备上的主页按钮或浏览过去的应用程序时,计时器仍会计时。因此,如果我在家里或其他应用程序屏幕中等待一段时间然后返回游戏,即使我已经离开应用程序,计时器也会计算时间。游戏状态与之前完全一样,只是计时器发生了变化。
可能是什么原因以及如何在应用程序没有焦点时阻止计时器计数?
最佳答案
Time.unscaledDeltaTime
的正常值通常在 0.01687395
左右。
使用 Time.unscaledDeltaTime
时,当您将焦点移出应用程序时,它仍在后台累加。返回应用程序后,Time.unscaledDeltaTime
的值将是您离开应用程序的 x 秒。
例如,如果您将焦点移出应用程序 15 秒然后返回,Time.unscaledDeltaTime
的输出在第一帧中将为 15,然后跳回到 0.01687395 左右
。 Time.deltaTime
变量没有这个问题,但它也不是一个选项,因为更改 Time.timeScale
会影响它。
解决方案是使用 OnApplicationFocus
和 OnApplicationPause
检测应用程序何时再次运行然后跳过在第一帧添加 Time.unscaledDeltaTime
因为第一帧是 Time.unscaledDeltaTime
实际上是您离开应用程序的 x 秒。
这是一个可行的解决方案:
public Text text;
float currentTime = 0;
private bool skipFrame = false;
void Update()
{
//Add only when we don't need to skip frame
if (!skipFrame)
{
currentTime += Time.unscaledDeltaTime;
text.text = currentTime.ToString();
}
//We need to skip frame. Don't use Time.unscaledDeltaTime this frame
else
{
skipFrame = false;
Debug.LogWarning("Filtered accumulated Time when Paused: " + Time.unscaledDeltaTime);
}
}
void OnApplicationFocus(bool hasFocus)
{
//Enable skipFrame when focoused in app
if (hasFocus)
{
//Debug.Log("Has focus");
skipFrame = true;
}
}
void OnApplicationPause(bool pauseStatus)
{
//Enable skipFrame when coming back from exiting app
if (!pauseStatus)
{
//Debug.Log("UnPaused");
skipFrame = true;
}
}
关于c# - 即使应用程序处于后台,Time.unscaledDeltaTime 仍然在计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503824/