Search code examples
c#unity-game-engine

Is it safe to assume SceneManager.sceneLoaded is called after all game objects' Awake()?


I'm currently testing a local scenario as a proof of concept in Unity 2022.3. Here's the setup:

Game Objects: There are dozens of game objects in the scene, each with MonoBehaviour script components. These scripts have their Awake() methods implemented to log a message using Debug.Log("Awake: " + this.GetType().Name).

GameManager Script: A script named GameManager subscribes to the SceneManager.sceneLoaded event with SceneManager.sceneLoaded += OnSceneLoaded. The OnSceneLoaded() method also logs a message using Debug.Log("OnSceneLoaded() called").

GameManager Placement: The GameManager script is attached to an arbitrary game object in the scene (not at the top or bottom of the hierarchy). No execution order is explicitly set for this script.

When I run the scene, the logs show all the awake messages before the OnSceneLoaded() message, which aligns with my expectations.

However, I'm concerned that this behavior might be specific to how my scene is set up in the editor, and there's a possibility it could change once the project is built and distributed to other machines.

My question is: Can I safely assume that SceneManager.sceneLoaded is always called after all Awake() methods of game objects in the hierarchy have been executed?


Solution

  • Yes, you can. The documentation says:

    OnEnable: Called when the object becomes enabled and active, always after Awake (on the same object) and before any Start.

    and:

    You can expect to receive the sceneLoaded notification after OnEnable but before Start for all objects in the scene.

    This means, you can safeily assume sceneLoaded is called after all game objects' Awake(

    For more, see the documentation about it.