我正在构建一个基于 vuforia 的增强现实应用程序。我需要为脚本的某些部分添加 sleep ,但我无法实现。
最佳答案
在没有看到您的代码/实际问题的情况下,很难给出比非常通用的答案更深入的答案:
每当你想在 Unity 中使用某种等待功能时,你应该使用
Coroutines
使用例如WaitForSeconds
, WaitUntil
, WaitWhile
等等。
private IEnumerator DoSomething()
{
// doing something
// waits 5 seconds
yield return new WaitForSeconds(5);
// do something else
}
您可以从另一个方法(在 MonoBehaviour 脚本中)使用
StartCoroutine(DoSomething());
调用
虽然协程更多地用于小动画,如平滑运动等简单计时器,但您也可以使用 Invoke
Invoke(nameof(DoSomething), 5.0f);
...
// will be called after 5 seconds
private void DoSomething()
{
// do something
}
简单更新定时器
当然,也可以在 MonoBehaviours 的 Update
方法中简单地等待,例如像
private float timer;
private bool activateSleep;
private void Update()
{
if(activateSleep)
{
timer += Time.deltaTime;
if(timer <= 0)
{
activateSleep = false;
}
else
{
// return so the rest of Update is not done
return;
}
}
// Otherwise do what you would usually do
}
public void ActivateSleep(float forSeconds)
{
timer = forSeconds;
activateSleep = true;
}
但你已经看到它变得多么“美丽”了......
关于unity3d - 如何在 Unity 脚本中实现 Thread.Sleep() 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55246755/