注意:AsyncOperation.isDone=false时,AsyncOperation. progress的最大值为0.9,=true时值才会变为1.0
1.代码如下:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class LoadingAsync : MonoBehaviour
{
private static string _nextSceneName = "";
[SerializeField]
private Slider loadingSlider;
[SerializeField]
private Text loadingText;
/// <summary>
/// 当前进度
/// </summary>
private int currentProgress;
/// <summary>
/// 目标进度
/// </summary>
private int targetProgress;
/// <summary>
/// 打开加载场景并且异步载入name场景
/// </summary>
/// <param name="name"></param>
public static void EnterScene(string name)
{
_nextSceneName = name;
SceneManager.LoadScene("LoadingScene");
}
private void Start()
{
DontDestroyOnLoad(this.gameObject);
StartCoroutine(LoadScene());
}
private IEnumerator LoadScene()
{
Debug.Log("EnterScene:" + _nextSceneName);
targetProgress = 0;
currentProgress = 0;
SetPercentUI(0);
yield return new WaitForEndOfFrame();
// 开始异步加载场景
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(_nextSceneName);
// 在未完全加载完之前不要让场景自动激活
asyncOperation.allowSceneActivation = false;
while (!asyncOperation.isDone)
{
// "asyncOperation.isDone = false"时"asyncOperation.progress"最大值是0。9
// 而只有"asyncOperation.allowSceneActivation = true;"激活场景后isDone才=true
if (asyncOperation.progress < 0.9f)
{
targetProgress = (int) (asyncOperation.progress * 100);
yield return LoadProgress();
}
else
{
// 场景加载完成后激活场景
asyncOperation.allowSceneActivation = true;
}
yield return null;
}
// 继续跑完进度条
targetProgress = 100;
yield return LoadProgress();
// 延迟销毁是为了让进度条跑到100%
Destroy(this.gameObject);
}
/// <summary>
/// 由于需要两次调用,在这里进行简单封装
/// </summary>
/// <returns>等一帧</returns>
private IEnumerator<WaitForEndOfFrame> LoadProgress()
{
while (currentProgress < targetProgress)
{
// 当前进度不断累加 (如果场景很小,可以调整这里的值 例如:+=10 +=20,来调节加载速度)
currentProgress += 20;
// 给UI进度条赋值
SetPercentUI(currentProgress);
//等一帧
yield return new WaitForEndOfFrame();
}
}
/// <summary>
/// 更新进度显示
/// </summary>
/// <param name="progress"></param>
private void SetPercentUI(int progress)
{
loadingSlider.value = (float) progress / 100;
loadingText.text = $"{progress}%";
}
}