C# 等待3秒后,协同程序不会加载新场景

C# 等待3秒后,协同程序不会加载新场景,c#,unity3d,coroutine,C#,Unity3d,Coroutine,我有这个剧本。这个想法是在游戏结束后触发LoadNextScene()。这将加载一个名为“干得好”的场景。该场景应打开约三秒,然后加载称为“开始菜单”的场景 这是成功的一半。游戏结束后,会加载“完成得很好”场景,但不会加载“开始菜单”,也不会打印MyCoroutine()中的调试消息 有什么不对劲 我也在想,我是否应该停止我的合作,就像我在代码中所做的那样好好练习 这是我的密码: public void LoadNextScene() { Debug.Log("NEXT

我有这个剧本。这个想法是在游戏结束后触发LoadNextScene()。这将加载一个名为“干得好”的场景。该场景应打开约三秒,然后加载称为“开始菜单”的场景

这是成功的一半。游戏结束后,会加载“完成得很好”场景,但不会加载“开始菜单”,也不会打印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之后
将卸载此脚本实例所属的当前场景→ 此游戏对象已被销毁→ 没有人再管理你的合作项目了

出于某种原因,您在启动它之后立即使用了
StopCoroutine
,这样它就不会运行了→ 不,这毫无意义;)


或者,您可以在
完成得很好
场景中使用一个单独的专用脚本,该脚本在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
随时触发它

把这个放在你的
做得好的
场景中,然后只做一件事

public void LoadNextScene()
{   
    SceneManager.LoadScene("Well done");
}
在您的原始脚本中