思路(需要协程)
- 创建AsyncOperation类的变量用来获取下个场景
- 将allowSceneActivation设置为false
- 在每帧中检测isDone
- 没加载好就将progress的值赋值给slider的value,因为progress的值是0-1的所以可以直接赋值给value
- 显示百分比直接将progress的值 * 100就可以
- 判断是否加载完成如果progress是0.9就代表加载完成了,因为我们上面设置了allowSceneActivation为false所以不会自动跳转需要再将值设置为true才会跳转
属性(AsyncOperation)
方法名 | 简介 |
allowSceneActivation | 自动加载下个场景 |
isDone | 是否加载好场景 |
progress | 数值是从0到1 显示加载场景的进程 如果allowSceneActivation是false,则最高到0.9 |
实例
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine;
using System.Collections;
public class LoadManager : MonoBehaviour
{
public GameObject loadScreen;
public Slider slider;
public Text text;
public void LoadNextLevel()
{
StartCoroutine(LoadLevel());
}
IEnumerator LoadLevel()
{
loadScreen.SetActive(true);
AsyncOperation operation = SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex - 1);
// 设置下一个场景为false
operation.allowSceneActivation = false;
// 判断是否加载好场景
while (!operation.isDone)
{
// progress数值是从0到1 显示加载场景的进程
// 如果下一个场景不设置为true会一直到0.9
slider.value = operation.progress;
// 显示文本百分比
text.text = (operation.progress * 100).ToString() + "%";
if (operation.progress >= 0.9f)
{
slider.value = 1f;
text.text = "Press AnyKey to continue";
// 按下任意按键显示下一个场景
if (Input.anyKeyDown)
{
operation.allowSceneActivation = true;
}
}
yield return null;
}
}
}