【问题标题】:How to Achieve Thread.Sleep() Functionality in Unity Script?如何在 Unity 脚本中实现 Thread.Sleep() 功能?
【发布时间】:2019-03-19 17:24:23
【问题描述】:

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

【问题讨论】:

    标签: unity3d vuforia thread-sleep


    【解决方案1】:

    如果没有看到您的代码/实际问题,很难给出一个比非常通用的答案更深入的答案:

    当你想要 Unity 中的某种等待功能时,你应该使用

    Coroutines

    使用例如WaitForSecondsWaitUntilWaitWhile 等等。

    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;
    }
    

    但你已经看到它变得多么“美丽”了......

    【讨论】:

    • 前一种方法对我不起作用。这需要使用特殊的库吗?
    • @AidanofVT 如您所见,所有链接都来自 Unity API .. 没有特殊库。究竟是什么不适合你?
    • 脚本进入 WaitForSeconds 调用,但不会导致程序等待。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 2023-03-23
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多