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.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Bug LoadSceneAsync doesn't set newly loaded scene active

Discussion in 'Scripting' started by stroibot, May 8, 2023.

  1. stroibot

    stroibot

    Joined:
    Feb 15, 2017
    Posts:
    90
    So I have this code that loads requested scene using `LoadSceneAsync` where `activateOnLoad` is defaulted to `true`, but loaded scene is not set as active. Why?

    Code (CSharp):
    1. protected async UniTask LoadSceneAsync(
    2.     AssetReference scene)
    3. {
    4.     if (_isLoading)
    5.     {
    6.         _logger.LogWarning(LogTag, "Scene load was requested, but scene load is in progress.");
    7.         return;
    8.     }
    9.  
    10.     _isLoading = true;
    11.     await _settings.LoadingScreenScene.LoadSceneAsync(LoadSceneMode.Additive);
    12.  
    13.     if (_currentScene.Scene.isLoaded)
    14.     {
    15.         _logger.Log(LogTag, $"Unloading '{_currentScene.Scene.name}' scene.");
    16.         await Addressables.UnloadSceneAsync(_currentScene);
    17.         _logger.Log(LogTag, "Scene was unloaded successfully.");
    18.     }
    19.  
    20.     // TODO: Remove
    21.     await UniTask.Delay(2000);
    22.  
    23.     _logger.Log(LogTag, "Starting scene loading.");
    24.     _currentScene = await scene.LoadSceneAsync(LoadSceneMode.Additive);
    25.     _logger.Log(LogTag, $"Scene '{_currentScene.Scene.name}' was loaded successfully.");
    26.     _isLoading = false;
    27.     await _settings.LoadingScreenScene.UnLoadScene();
    28. }
    Bing AI suggests using this:
    Code (CSharp):
    1. await UniTask.NextFrame();
    2. SceneManager.SetActiveScene(_currentScene.Scene);
    Yeah, it works, but this is an ugly hack, damn....
     
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,051
    Well, the naming is a bit unfortunate. The
    activateOnLoad
    refers the step after scene loading, where all the scripts in the scene are executed and their Awake/OnEnable called. It does not refer to the "active scene", those are separate concepts. You use
    activateOnLoad
    (called allowSceneActivation outside of Addressables) to pre-load a scene without immediately executing all the scripts it contains.

    Calling
    SetActiveScene
    is the only way to make an asynchronously loaded scene the active scene after loading it. Unity's documentation on SetActiveScene says this:
     
    Last edited: May 9, 2023
  3. stroibot

    stroibot

    Joined:
    Feb 15, 2017
    Posts:
    90
    Thanks!