异步加载在很多游戏中都会用到,特别是场景偏大的游戏中。那我们今天就一起来学习一下如何使用异步加载吧。(所有的步骤说明,要点都在代码中注释了,觉得贴心就给个赞吧!)
话不多说,直接上代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement; //引入命名空间
public class AsyncLoading : MonoBehaviour
{
//这里为了方便演示就直接拖组件赋值了哈
public Text loadingTxt; //进度条加载进度数值显示
public Slider slider; //进度条
AsyncOperation operation;
void Start ()
{
slider.value = 0;
StartCoroutine(LoadingAsync());
}
IEnumerator LoadingAsync()
{
operation = SceneManager.LoadSceneAsync("需要加载的场景名称");
operation.allowSceneActivation = false;//为了阻止加载完成就跳转场景--我们需要等loadingTxt到100%时候才跳转
while (!operation.isDone) //未加载完时
{
if (operation.progress<0.9f)
{
slider.value = operation.progress;
}
else
{
slider.value = 1.0f;//因为加载到0.9的时候就已经完成了加载,所以我们需要在此赋值为1--为了让loadingTxt显示100%
}
loadingTxt.text = (int)(slider.value * 100) + "%";
if (slider.value>=0.9f) //当loadingTxt显示100%的时候就跳转场景
{
operation.allowSceneActivation = true;
}
yield return null;
}
}
}
就这样异步加载就搞定啦。欢迎大家留言分享交流