Unity cannot set ActiveScene

不问归期 提交于 2019-12-01 14:53:16
Programmer

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.

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