SceneManager.LoadSceneAsync()

517 阅读2分钟

已经将post融入进“场景加载机制”:juejin.cn/post/713584…

Link1:stackoverflow.com/questions/5…

Link2:stackoverflow.com/questions/6…

Link(3)在Unity中如何加载场景:gamedevbeginner.com/how-to-load…

对yield return SceneManager.LoadSceneAsync()的条件检测发生在Awake和Start之间,这就意味着这在新场景成功加载后的那一帧,新场景会首先调用所有该场景所有组件的Awake,然后再执行yield return SceneManager.LoadSceneAsync()后面的代码,接着在调用所有组件的start方法。

其实,整体而言SceneManager.LoadSceneAsync()和SceneManager.loadSceneAsync再直接使用时可以认为是一致的,在功能上没有明显的区别。区别在于LoadSceneAsync会返回一个AsyncOpreation(实时的跟踪异步操作的状态),从而可以被协程利用从而判断场景是否加载成功,实现场景的异步加载。要注意,所有的异步操作 (Resources.LoadAsync, AssetBundle.LoadAssetAsync, AssetBundle.LoadAllAssetAsync, SceneManager.LoadSceneAsync)的都是在一个名为BackGround Thread的独立线程中进行处理,而不是MainThread。可以通过Application.backgroundLoadingPriority设置这些异步操作的优先顺序:docs.unity3d.com/ScriptRefer…

同时,我们应该将SceneManager.loadSceneAsync()等这些方法仅仅视为向Unity引擎本身发出的指令(C#只是一种脚本语言),其本身并没有实现任何处理异步任务的核心逻辑,而只是指令Unity去完成,并且返回一个AsyncOpreation的C#对象去实时的跟踪异步任务的处理进度,并且可以通过这个对象干预异步任务。所以C#作为一种用户脚本语言,架起了与Unity引擎内部进行沟通的桥梁。

Question:

There are two phases in SceneManager.LoadSceneAsync().

Firstly there's the preload phase. Second the activation phase.

What is exactly loading in each phase?

Answe:

Pre-loading Scene:

A scene is loaded in the background. During this time, the resources such as textures, audios and 3D models referenced in that scene are loaded.

Activating Scene:

When the loaded scene is activated, the current scene is unloaded and the loaded scene will be active. When it becomes active, it will start executing the scripts referenced in that scene.

SceneManager.LoadSceneAsync will load the scene in the background. When the scene is loaded, it will be automatically activated. When activation is done, Unity will enable that loaded scene and the loaded scene will become the current scene.

Controlling Scene Activation:

Sometimes, you want to load the next scene when the current game is about to finish but you don't want it to activate it until the current game play is done. You are pre-loading the scene. This can be done by setting the AsyncOperation.allowSceneActivation property returned by the LoadSceneAsync function to false. By setting it to false, the scene will load but will not activate or run until you set it to true. Let's say you have finished playing the current scene, you can then activate the next scene which actually reduces the amount of time your player has to wait for the scene to finish loading. Loading and activating the next scene when the game is over will take more time than simply activating the scene.