Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question SceneManager.UnloadSceneAsync destroys object in a different scene.

Discussion in 'Scripting' started by Bean_Office, Nov 28, 2022.

  1. Bean_Office


    Jun 18, 2018
    I have 2 scenes: Game and Level1. Game contains the player, GameManager and some other things. When the player dies I unload Level1 and then load it again. For some reason the Player in Game gets destroyed, when I call the Unload.

    Code (CSharp):
    1. IEnumerator ResetLevelRoutine()
    2.     {
    3.         yield return new WaitForSeconds(1.5f);
    4.         LoadedUI.Singleton.ScreenFadeIn();
    5.         yield return new WaitForSeconds(0.3f);
    6.         Debug.Log("p1");
    7.         Debug.Log(FindObjectOfType<PlayerMovement>() != null);
    8.         AsyncOperation unload = SceneManager.UnloadSceneAsync(CurrentLevel);
    9.         yield return new WaitWhile(() => unload.isDone);
    10.         Debug.Log("p2");
    11.         Debug.Log( FindObjectOfType<PlayerMovement>() != null);
    12.         AsyncOperation load = SceneManager.LoadSceneAsync(CurrentLevel, LoadSceneMode.Additive);
    13.         yield return new WaitWhile(() => load.isDone);
    14.         Debug.Log("p3");
    15.         Debug.Log(FindObjectOfType<PlayerMovement>() != null);
    16.         OnLevelLoaded?.Invoke(SceneManager.GetActiveScene(), true);
    17.         GameManager.PlayerRespawnEvent?.Invoke();
    18.         LoadedUI.Singleton.ScreenFadeOut();
    19.         Debug.Log("p4");
    20.         Debug.Log(FindObjectOfType<PlayerMovement>() != null);
    21.     }
    It will print p1 true,
    but then print p2 false.
  2. Kurt-Dekker


    Mar 16, 2013
    Find what scene the player is in. If it's in the wrong scene, move it when you Instantiate<T>() it. By default it goes into the current active scene.