如何在Unity脚本中实现Thread.Sleep()功能?

问题描述 投票:1回答:1

我正在构建基于vuforia的增强现实应用程序。我需要为脚本的某些部分添加睡眠但我无法实现它。

unity3d vuforia thread-sleep
1个回答
2
投票

在没有看到您的代码/实际问题的情况下,很难给出比非常通用更进一步的答案:

无论何时你想在Unity中使用某种等待功能,你都应该使用CoroutinesWaitForSecondsWaitUntilWaitWhile等。

private IEnumerator DoSomething()
{
    // doing something

    // waits 5 seconds
    yield return new WaitForSeconds(5);

    // do something else
}

你从另一个方法(在MonoBehaviour脚本中)开始使用

StartCoroutine(DoSomething());

当然,也可以简单地在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;
}

但你已经看到了如何“美丽”......

© www.soinside.com 2019 - 2024. All rights reserved.