Unity cannot set ActiveScene

走远了吗. 提交于 2019-12-01 12:59:23

问题


I'm switching scenes:

SceneManager.LoadScene("Scene2");
Debug.Log("Current scene: " + SceneManager.GetActiveScene().name);

Debug says:

Current scene: Scene1

I've tried this also:

SceneManager.LoadScene("Scene2");
StartCoroutine(WaitUntilEndOfFrame());
Debug.Log("Current scene: " + SceneManager.GetActiveScene().name);

private IEnumerator WaitUntilEndOfFrame() {

yield return new WaitForEndOfFrame();

}

Still says

Current scene: Scene1.

I've tried SetActiveScene(SceneManager.GetSceneByBuildId(1));

I've tried launching that as a coroutine, I've tried that and waiting for 5 seconds. Still ActiveScene is Scene1, even though the scene changes in Unity. Nothing changes the active scene...


回答1:


When SceneManager.LoadScene("Scene2"); is called, the scene does not unload until next frame. So, if Debug.Log("Current scene: " + SceneManager.GetActiveScene().name); called right after that, it will return the name of the current scene not that scene is just loaded.

Even when you use coroutine and wait for a frame, that wouldn't work either because after a frame, the script and GameObject will be destroyed and your Debug.Log("Current scene: " + SceneManager.GetActiveScene().name); won't get to run.

Don't call SceneManager.GetActiveScene().name right after SceneManager.LoadScene("Scene2");. Put SceneManager.GetActiveScene().name in the Awake or Start function and you will be able to get scene name after the scene loads.

EDIT:

Another thing to do to is subscribe to the SceneManager.sceneLoaded event. Now, call SceneManager.LoadScene("Scene2");. When scene is done loading, the registered function should be called.

void Start()
{
    SceneManager.LoadScene("Scene2");
}

void OnEnable()
{
    SceneManager.sceneLoaded += this.OnLoadCallback;
}

private void OnLoadCallback(Scene scene, LoadSceneMode sceneMode)
{
    UnityEngine.Debug.Log("Current scene: " + SceneManager.GetActiveScene().name);
}

Finally, if you don't add the scenes to the Build Settings, SceneManager.LoadScene("Scene2"); won't even work so your current scene will still be your current scene. Below is how to add scenes to the Build Settings.



来源:https://stackoverflow.com/questions/43420223/unity-cannot-set-activescene

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!