Help: LoadScene/GetSceneByName

Hi. I’m learning Unity and C#, and I’m having trouble with loading a new scene. This code works fine:

    public string sceneName;

    private void OnTriggerEnter2D(Collider2D collision) {
        Player player = collision.GetComponent<Player>();
            if(player)
            {
                 SceneManager.LoadScene("TavernGround");
            }
    }

But, i want to move my player to another scene as well. So, when i do that:

    public string sceneName;

    private void OnTriggerEnter2D(Collider2D collision) {
        Player player = collision.GetComponent<Player>();
            if(player){
                Scene sceneToLoad = SceneManager.GetSceneByName("TavernGround");
                SceneManager.MoveGameObjectToScene(collision.gameObject, sceneToLoad);
            }
    }

It doesn’t work. Scene object is Null. Even if I replace var sceneName with actual name, it still doesn’t work. Neither GetSceneByBuildIndex. What am I doing wrong? Or there is other way to move player to other scene?

Scenes don’t load until end of frame, and they do so simultaneous to unloading the previous scene, which is likely where your player is.

One way is to mark him DontDestroyOnLoad() and he’ll stick around. Objects marked DDOL must be Destroy()ed explicitly, or else moved back to another scene that gets unloaded. The DDOL mechanism is just a special scene that never unloads.

This is commonly where a GameManager construct becomes useful. Google for details on those.

Also, importantly, GetSceneByName/GetSceneByBuildIndex only work for loaded scenes. The scene data doesn’t really exist until the scene has been loaded.