Documenting the dark corners of the Unity Engine.
Scene loading and unloading happens at the start of the Update loop, within the
EarlyUpdate.UpdatePreloading phase of the PlayerLoop, and once during the Initialization phase of the player, before the first Update loop.
Player Loop Phases:
The scene loading queue is a pipeline, and only one AsyncOperation can progress at a time. Calling
SceneManager.UnloadSceneAsync adds a new AsyncOperation onto the end of the queue.
UpdatePreloading phase, Unity will execute the next operation in the scene loading queue.
The scene loading pipeline only seems to execute a single operation, every other frame.[research needed] If you have 3 small scenes in the pipeline (Scene1, Scene2, Scene3), loading additively, the engine will load them at the following times:
The Engine fully “flushes” the scene loading queue during initialization. This works differently than the way Unity loads scenes during the EarlyUpdate.
All AsyncOperations that are queued during initialization are fully loaded during initialization. For example, if
SceneManager.LoadSceneAsync is called in the Awake of the very first scene1), the engine will load this new scene before finishing Initialization.
Scene unloads are probably flushed if they are in the pipeline, too.[research needed]
Scenes are built during standalone build in the following way:
EditorSceneManager.sceneOpenedcallback is called.
Here is an example of a scene loading additively in the middle of a game, in the editor. Note that:
ISerializationCallbackReceiver.OnAfterDeserializeis called before the async loading of heavy scene resources (e.g. textures) so can be used for running scene-specific thread-aware code early in the loading process.3)
LoadSceneMode.Additive, using the
SceneManager.sceneLoadedcallback and setting
SceneManager.SetActiveScene(scene)within this callback results in Unity replacing the currently loaded occlusion culling data with the occlusion culling data from this newly loaded scene. This goes directly against what is documented, which states Unity will only use the culling data from the first loaded scene. This undocumented behavior has been tested in 2018.4-2020.3, and may or may not work in other versions of Unity.