Unity LoadSceneAsync异步加载场景的时候,通常会卡在89%,并且在整个加载的过程中易出现加载快慢不一,给用户造成卡顿的假象。偶然在A计划中看到,特此分享给各位。
代码中的scence指的是上图中红色的id号,也可以为场景的名字。
以下代码,亲测可用,话不多说,直接上代码:
public class Loding : MonoBehaviour
{
public Image processView;//一张图片,将Image 的Image Type 改为Filled模式即可,参照文末图片。
private void Start()
{
LodeGameMethod();
}
public void LodeGameMethod()
{
StartCoroutine(StartLoding(2));
}
//scence 为场景在
private IEnumerator StartLoding(int scence)
{
//当前加载进度
int displayProgress = 0;
//目标加载进度
int toProgress = 0;
//开启异步加载
AsyncOperation op = SceneManager.LoadSceneAsync(scence);
//在场景为加载到100不允许场景被激活
op.allowSceneActivation = false;
while (op.progress<0.9f)
{
toProgress = (int)op.progress * 100;
while (displayProgress< 90)
{
++displayProgress;
Debug.Log(displayProgress);
SetLoadingPercentage(displayProgress);
yield return new WaitForEndOfFrame();
}
}
//Unity通常会加载到89%便会卡顿,此时场景已经加载完毕
toProgress = 100;
while (displayProgress<toProgress)
{
++displayProgress;
SetLoadingPercentage(displayProgress);
yield return new WaitForEndOfFrame();
}
//激活已经加载的场景
op.allowSceneActivation = true;
}
/// <summary>
/// 试试更新进度条
/// </summary>
/// <param name="displayProgress"></param>
private void SetLoadingPercentage(int displayProgress)
{
Debug.LogError(displayProgress / 100);
processView.fillAmount = (float)displayProgress / 100;
}
}