Unity非同步載入場景與載入進度條
阿新 • • 發佈:2018-12-30
非同步載入場景分為A、B、C三個場景
A場景是開始場景;B場景是載入場景(進度條載入顯示);C場景是目標場景
在A場景中新增一個按鈕,觸發函式:
//非同步載入新場景
public void LoadNewScene()
{
//儲存需要載入的目標場景
Globe.nextSceneName = "Scene";
SceneManager.LoadScene("Loading");
}
在B場景中新增一個指令碼,掛載到Camera下
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Globe { public static string nextSceneName; } public class AsyncLoadScene : MonoBehaviour { public Slider loadingSlider; public Text loadingText; private float loadingSpeed = 1; private float targetValue; private AsyncOperation operation; // Use this for initialization void Start () { loadingSlider.value = 0.0f; if (SceneManager.GetActiveScene().name == "Loading") { //啟動協程 StartCoroutine(AsyncLoading()); } } IEnumerator AsyncLoading() { operation = SceneManager.LoadSceneAsync(Globe.nextSceneName); //阻止當載入完成自動切換 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.Lerp(loadingSlider.value, targetValue, Time.deltaTime * loadingSpeed); if (Mathf.Abs(loadingSlider.value - targetValue) < 0.01f) { loadingSlider.value = targetValue; } } loadingText.text = ((int)(loadingSlider.value * 100)).ToString() + "%"; if ((int)(loadingSlider.value * 100) == 100) { //允許非同步載入完畢後自動切換場景 operation.allowSceneActivation = true; } } }
這裡需要注意的是使用AsyncOperation.allowSceneActivation屬性來對非同步載入的場景進行控制
為true時,非同步載入完畢後將自動切換到C場景
最後附上效果圖
個人網站:www.liujunliang.com.cn
部落格地址:blog.liujunliang.com.cn
本人也在尋找一份遊戲開發實習工作,如果大佬們需要開發人員,請把我帶走
作品的話可以私聊我哦!