Search Unity

Question SceneManager.UnloadSceneAsync destroys object in a different scene.

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

  1. Bean_Office

    Bean_Office

    Joined:
    Jun 18, 2018
    Posts:
    16
    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:
    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

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    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.