Unity3d异步场景切换Application.LoadLevelAsync
发表于2019-01-31
当使用Application.LoadLevel同步加载:进入的场景先进行资源的加载,待场景中所有的资源加载完成,才能进行场景和切换。并且原场景资源会立刻销毁
异步加载
Application.LoadLevelAsync() : 异步场景切换,Unity会在后台线程中加载所有资源,并保存之前场景的游戏对象,我们在加载过程中获取到加载的进度,可以播放一个真实的进度条,来看加载进度。
注意
异步加载只能获取90%,剩下10%需要自己设置,所有要进行优化,在最后%10做一个假加载
这个假加载如果读条完了,但是实际场景如果没有加载完,就会出现进度条以满,但是还没进入场景的情况(好像卡住了)
代码脚本例子
在读条UISlider的脚本对象上加此脚本
using UnityEngine; using System.Collections; public class ProgressBar : MonoBehaviour { public UISlider _progress; void Awake(){ _progress = GetComponent<UISlider> (); } //使用协程 void Start(){ StartCoroutine (LoadScene ()); } IEnumerator LoadScene(){ //用Slider 展示的数值 int disableProgress = 0; int toProgress = 0; //异步场景切换 AsyncOperation op = Application.LoadLevelAsync ("GameScene"); //不允许有场景切换功能 op.allowSceneActivation = false; //op.progress 只能获取到90%,最后10%获取不到,需要自己处理 while (op.progress < 0.9f) { //获取真实的加载进度 toProgress = (int)(op.progress * 100); while (disableProgress < toProgress) { ++disableProgress; _progress.value = disableProgress / 100.0f;//0.01开始 yield return new WaitForEndOfFrame (); } } //因为op.progress 只能获取到90%,所以后面的值不是实际的场景加载值了 toProgress = 100; while (disableProgress < toProgress) { ++disableProgress; _progress.value = disableProgress / 100.0f; yield return new WaitForEndOfFrame (); } op.allowSceneActivation = true; } }