【问题标题】:Delay Switch Scene C# Unity延迟切换场景 C# Unity
【发布时间】:2019-07-18 23:33:14
【问题描述】:

我正在创建一个将 QR 码检测为目标图像的 AR 应用程序。我正在检测 4 个二维码,一旦检测到二维码,就需要加载一个新场景。我在 OnTrackingFound 事件下的 DefaultTrackableEventHandler 脚本中使用了 switch 语句。

switch 语句有效。一旦检测到目标图像,它就会切换到新场景。问题是它切换得太快了。我怎么能延迟这个?我已经尝试过 Invoke() 方法和 IEnumarator 方法,但没有成功。

这是我的代码:

protected virtual void OnTrackingFound()
    {
        var rendererComponents = GetComponentsInChildren<Renderer>(true);
        var colliderComponents = GetComponentsInChildren<Collider>(true);
        var canvasComponents = GetComponentsInChildren<Canvas>(true);

        // Enable rendering:
        foreach (var component in rendererComponents)
            component.enabled = true;

        // Enable colliders:
        foreach (var component in colliderComponents)
            component.enabled = true;

        // Enable canvas':
        foreach (var component in canvasComponents)
            component.enabled = true;


// This is where it detects the image target and loads new scene.
        switch (mTrackableBehaviour.TrackableName)
        {
          case "HLQRj":
                Invoke("PrintGRV", 5);
                SceneManager.LoadScene("PrintGRV");
                break;
           case "FSQRj":
                Invoke("PrintGRV", 5);
                SceneManager.LoadScene("PrintGRV");
                break;
           case "BPQRj":
                Invoke("PrintGRV", 5);
                SceneManager.LoadScene("PrintGRV");
                break;
           case "SPQRj":
                Invoke("PrintGRV", 5);
                SceneManager.LoadScene("PrintGRV");
                break;

        }

    }

【问题讨论】:

    标签: c# unity3d timer switch-statement


    【解决方案1】:

    这取决于您需要等待多长时间和等待什么……如果您想等待,例如对于固定的时间延迟,您可以简单地使用Coroutine,例如使用WaitForSeconds

    private IEnumerator SwitchScene()
    {
        // waits for 2 seconds
        yield return new WaitForSeconds(2);
    
        SceneManager.LoadScene("PrintGRV");
    }
    

    然后像这样运行它

    switch (mTrackableBehaviour.TrackableName)
    {
        case "HLQRj":
            Invoke("PrintGRV", 5);
            StartCoroutine(SwitchScene());
            break;
        //...
    }
    

    如果你想等到某个其他异步方法完成,你也可以例如等待一个 bool 标志变为真,正如 Draco18s 正确提到的,你可以简单地使用 WaitUntil

    private bool xyIsDone = false;
    
    private IEnumerator SwitchScene()
    {
        // wait until xyIsDone becomes true
        WaitUntil(xyIsDone);
    
        SceneManager.LoadScene("PrintGRV");
    }
    

    【讨论】:

    • 我还要注意WaitUntil (() =&gt; xyIsDone) 的作用与循环相同。
    • @Draco18s 你是对的,我总是忘记那个!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多