异步加载场景以及进度条
1.我自己百度搜到的,用起来不错,记录一下
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Loading : MonoBehaviour
{
private Slider slider;
private Text sliderText;
AsyncOperation async;
//读取场景的进度,它的取值范围在0 - 1 之间。
// int progress = 0;
// Start is called before the first frame update
void Awake()
{
sliderText = transform.Find("Loading/Slider/Text").GetComponent<Text>();
slider = transform.Find("Loading/Slider").GetComponent<Slider>();
}
void Start() {
StartCoroutine(LoadingScene());
}
//设置滑动条
private void setProgressValue(int value) {
slider.value = value*0.01f;
// Debug.Log("slider.value" + async.progress);
sliderText.text = value.ToString() + "%";
}
private IEnumerator LoadingScene()
{
async = SceneManager.LoadSceneAsync(GameManager.Instance.targetScene); //异步加载场景
async.allowSceneActivation = false; //假如加载完成,也不进入场景
int toProgress = 0;
int showProgress = 0;
//测试了一下,进度只有0和0.9,坑,没有中间数
while (async.progress < 0.9f)
{
toProgress = (int)(async.progress * 100);
// Debug.Log("toProgress" + toProgress);
while (showProgress < toProgress )
{
showProgress++;
setProgressValue(showProgress);
yield return new WaitForEndOfFrame(); //等候一帧
}
yield return new WaitForEndOfFrame(); //等候一帧
}
//计算0.9---1 其实0.9就是加载好了,我估量真正进入到场景是1
toProgress = 100;
while (showProgress < toProgress)
{
showProgress++;
setProgressValue(showProgress);
yield return new WaitForEndOfFrame(); //等候一帧
}
async.allowSceneActivation = true; //假如加载完成,能够进入场景
}
}
注意一点,加载大的场景用异步加载SceneManager.LoadSceneAsync,例如场景A到场景B到场景C,场景B是进度条,A先同步加载SceneManager.LoadScene到B,B再异步加载到C,而场景B就是挂上面的脚本。如果A异步加载B,那么B异步加载C,可能会出错,我就遇到过,一直加载不到C场景,并且进度条卡死,电脑死机