等待 3 秒后协程不会加载新场景

Coroutine wont load new scene after wait for 3 seconds

我得到了这个脚本。这个想法是在完成游戏后触发 LoadNextScene()。这将加载一个名为“Well done”的场景。该场景应打开约三秒钟,然后加载名为“开始菜单”的场景。

这成功了一半。游戏结束后,加载“Well done”场景,但未加载“开始菜单”,也未打印 MyCoroutine() 中的调试消息。

有什么问题吗?

我也在考虑是否应该像我在代码中那样停止我的协程作为良好实践?

这是我的代码:

public void LoadNextScene()
{   
    Debug.Log("NEXT SCENE WAIT 3 sec");
    SceneManager.LoadScene("Well done");
    Debug.Log("Start waiting");
    StartCoroutine(MyCoroutine());
    StopCoroutine(MyCoroutine());
}

private IEnumerator MyCoroutine()
{
    yield return new WaitForSeconds(3);
    Debug.Log("Finish waiting and load start menu");
    SceneManager.LoadScene("Start Menu");
}

好吧,在你的第一个 SceneManager.Load 这个脚本实例所属的当前场景被卸载 → 这个 GameObject 被销毁 → 没有人再 运行 你的协程了。

出于某种原因,您在启动后立即额外使用了 StopCoroutine,所以它不会 运行 → 不,这没有任何意义;)


或者,您可以在 Well Done 场景中简单地添加一个单独的专用脚本,它会在 3 秒后自动返回主菜单。

实际上,为了使其更加灵活和可重用,您可以拥有一个像

这样的组件
public class SwitchSceneDelayed : MonoBehaviour
{
    // Configure these in the Inspector
    [SerializeField] bool autoSwitch = true;
    [SerializeField] float _delay = 3f;
    [SerializeField] string targetScene = "Start menu";

    private void Start()
    {
        if(autoSwitch) StartCoroutine(SwitchDelayedRoutine(_delay));
    }

    public void SwitchDelayed()
    {
        StartCoroutine(SwitchDelayedRoutine(targetScene, _delay));
    }

    public void SwitchDelayed(float delay)
    {
        StartCoroutine(SwitchDelayedRoutine(targetScene, delay));
    }

    public void SwitchDelayed(string scene)
    {
        StartCoroutine(SwitchDelayedRoutine(scene, _delay));
    }

    public void SwitchDelayed(string scene, float delay)
    {
        StartCoroutine(SwitchDelayedRoutine(scene, delay));
    }

    private IEnumerator SwitchDelayedRoutine(string scene, float delay)
    {
        Debug.Log($"Started waiting for {delay} seconds ...");
        yield return new WaitForSeconds (delay);

        SceneManager.LoadScene(scene);
    }
}

因此此脚本允许您在 delay 秒后延迟切换到 targetScene 中配置的另一个场景。如果启用 autoSwitch 例程将立即开始,否则您可以随时通过调用 SwitchDelayed.

触发它

把它放在你的 Well Done 场景中,然后只做

public void LoadNextScene()
{   
    SceneManager.LoadScene("Well done");
}

在您的原始脚本中。