Unity3D 場景切換非同步載入進度
阿新 • • 發佈:2019-02-20
非同步載入場景分為A、B、C三個場景
A場景是開始場景;B場景是載入場景(進度條載入顯示);C場景是目標場景
在A場景中新增一個按鈕,觸發函式:
//非同步載入新場景
public void LoadNewScene()
{
//儲存需要載入的目標場景
Globe.nextSceneName = "Scene";
SceneManager.LoadScene("Loading");
}
在B場景中新增一個指令碼(AsyncLoadScene),掛載到Camera下
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Globe { public static string nextSceneName; /// <summary> /// 非同步載入場景 /// </summary> /// <param name="sceneName">場景名字</param> /// <param name="isAsync">是否使用非同步載入</param> public static void LodingScene(string sceneName, bool isAsync = true) { //清理Unity垃圾 Resources.UnloadUnusedAssets(); //清理GC垃圾 System.GC.Collect(); //是否使用非同步載入 if (isAsync) { //賦值載入場景名稱 nextSceneName = sceneName; //跳轉到LoadingScene場景 SceneManager.LoadScene("LoadingScene"); } else { SceneManager.LoadScene(sceneName); } } } /// <summary> /// 非同步載入指令碼 /// </summary> public class AsyncLoadScene : MonoBehaviour { public Slider loadingSlider; //public Text Tips; //public Text loadingText; //private float loadingSpeed = 1; //private float targetValue; private AsyncOperation operation; private int displayProgress; private int toProgress; void Start() { loadingSlider.value = 0; loadingSlider.maxValue = 100; if (SceneManager.GetActiveScene().name == "LoadingScene") { //啟動協程 StartCoroutine(AsyncLoading()); } } private IEnumerator AsyncLoading() { operation = SceneManager.LoadSceneAsync(Globe.nextSceneName); operation.allowSceneActivation = false; while (operation.progress < 0.9f) { toProgress = (int)operation.progress * 100; while (displayProgress < toProgress) { ++displayProgress; SetLoadingPercentage(displayProgress); yield return new WaitForEndOfFrame(); } } toProgress = 100; while (displayProgress < toProgress) { ++displayProgress; SetLoadingPercentage(displayProgress); yield return new WaitForEndOfFrame(); } operation.allowSceneActivation = true; } private void SetLoadingPercentage(int Percentage) { loadingSlider.value = Percentage; //loadingText.text = Percentage + "%"; } }
這裡需要注意的是使用AsyncOperation.allowSceneActivation屬性來對非同步載入的場景進行控制
為true時,非同步載入完畢後將自動切換到C場景
最後附上效果圖