进度条制作的过程中最重要的API:AsyncOperation.progress。可以获取到异步操作时的进度。
官网描述:获取操作进度。(只读)
返回操作的进度。(只读) 这将返回操作的剩余进度。当进度浮点值到达 1.0 并调用isDone 时,操作结束。如果将 allowSceneActivation 设置为 false,则进度将在 0.9处停止,直到被设置为 true。这对于创建加载条来说极其有用。
- 要制作进度条,首先场景加载得用异步加载,这样才能获取得到它异步操作时的进度。使用AsyncOperation.progress它的值是瞬变的,没有一点一点增加的过程,所以如果想要一点一点增加的效果,就得用到协程在每一帧中增加一点来达到一点一点增加的效果,用AsyncOperation.isDone来当作判断条件。当AsyncOperation.progress的值到达0.9f时便会停下,得等AsyncOperation.allowSceneActivate为true,它的值才会为1.0f,此时AsyncOperation.isDone也会为true,整个异步操作便结束了。
- 以下是一点一点增加的进度条:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadSceneFromProgressBar : MonoBehaviour
{
public Image progressBar = null;
public Text progressText = null;
public Button btn_loadScene = null;
private float progressValue=0.0f;
private void Init()
{
progressText.text = "Loading : 0%";
}
private void Start()
{
btn_loadScene.onClick.AddListener(LoadScene);
Init();
}
private void LoadScene()
{
StartCoroutine(Load());
}
private IEnumerator Load()
{
yield return null;
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync("Scene2");
asyncOperation.allowSceneActivation = false;
while (!asyncOperation.isDone)
{
progressValue+=0.01f;
progressText.text = "Loading : " + (int)(progressValue * 100) + "%";
progressBar.fillAmount = progressValue;
if (asyncOperation.progress >= 0.9f&&progressValue>=0.9f)
{
progressText.text = "Loading : 100%";
progressBar.fillAmount = 1.0f;
// yield return new WaitForEndOfFrame();
asyncOperation.allowSceneActivation = true;
}
yield return null;
}
}
}