實現異步加載場景不僅需要當前場景和目標場景,同時還需要一個中間場景實現目標場景的加載過程。
對於中間場景的構建可添加進度條(slider組件)和進度顯示(Text組件)。同時在MainCamera上掛在腳本內容如下:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SceneControl
{
public static string targetSceneName;
public static void LoadScene(string sceneName)
{
targetSceneName = sceneName;
SceneManager.LoadScene("MiddleScene");
}
}
public class LoadScene : MonoBehaviour
{
//將Slider組件拖入此位置
public Slider loadingSlider;
//將Text組件拖入此位置
public Text loadingText;
private float loadingSpeed = 0.4f;
private float targetValue;
private AsyncOperation operation;
// Use this for initialization
void Start()
{
StartCoroutine(AsyncLoading());
}
IEnumerator AsyncLoading()
{
operation = SceneManager.LoadSceneAsync(SceneControl.targetSceneName);
//阻止當加載完成自動切換
operation.allowSceneActivation = false;
yield return operation;
}
// Update is called once per frame
void Update()
{
targetValue = operation.progress;
if (operation.progress >= 0.9f)
{
//operation.progress的值最大爲0.9
targetValue = 1.0f;
}
if (targetValue != loadingSlider.value)
{
loadingSlider.value = Mathf.MoveTowards(loadingSlider.value, targetValue, Time.deltaTime * loadingSpeed);
}
loadingText.text = ((int)(loadingSlider.value * 100)).ToString() + "%";
if ((int)loadingSlider.value == 1)
{
//允許異步加載完畢後自動切換場景
operation.allowSceneActivation = true;
}
}
}
在當前場景中使用SceneControl.LoadScene(string sceneName)靜態方法就可以加載目標場景。