Unity異步加載場景

? ? ? ?加載場景的功能想必在游戲開發中是十分常見的了。如果想從一個場景過渡到另一個包含資源較多的場景,必然需要等待一段時間,這時候就需要有一個過渡場景來告訴用戶當前加載的進度。 本案例使用滑動條和文字來顯示加載進度。


using System.Collections;

using UnityEngine;

using UnityEngine.UI;

using UnityEngine.SceneManagement;

public class Loading : MonoBehaviour

{

? ? AsyncOperation async;? ? //異步對象

? ? public string SceneName;

? ? public Slider loadingSlider;? ? //顯示進度的滑動條

? ? public Text loadingText;? ? ? ? ? //顯示進度的文本

? ? private float loadingSpeed = 1;

? ? private float targetValue;

? ? void Start()

? ? {

? ? ? ? loadingSlider.value = 0.0f;

? ? ? ? StartCoroutine("LoadScene");

? ? }


? ? IEnumerator LoadScene()

? ? {

? ? ? ? async = SceneManager.LoadSceneAsync(SceneName);

? ? ? ? //async.allowSceneActivation = false;

? ? ? ? print("Loading:"+ async);

? ? ? ? yield return async;

? ? }

? ? void Update()

? ? {

? ? ? ? if (async == null) return;

? ? ? ? targetValue = async.progress;

? ? ? ? //值最大為0.9

? ? ? ? if (async.progress >= 0.9f)

? ? ? ? {

? ? ? ? ? ? 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)

? ? ? ? ? ? async.allowSceneActivation = true;

? ? }

}


? ? ? ?需要注意的是:場景加載過程中,可能會出現一些耗時的卡線程的操作(比如從數據庫讀取大量數據到內存),此時應當將相關代碼放進另一線程中執行。主線程和副線程同時進行,在副線程完成之前,如果主線程沒事做就一直等待,當副線程運行完畢時,給主線程發出信號,此時再完成場景的加載動畫。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。