Unity3D_異步加載場景(進度條)


  1. 創建兩個場景:現在的場景“NowScene”,要加載的場景“LoadScene”;
  2. “NowScene”如圖所示,“LoadScene”任意;
  3. 創建腳本“AsyncLoadScene”,復制如下代碼,掛在到Canvas上;
  4. 推拽"Slider"和"Text"到面板上;
  5. 注意將要加載的場景添加到《Scenes In Build》,否則加載時回報空引用。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class AsyncLoadScene : MonoBehaviour
{
    // 進度條
    public Slider loadingSlider;
    // 文字顯示加載進度
    public Text loadingText;
    // 進度條的行進速度
    private float SliderLoadSpeed = 1;
    // 場景加載類的對象
    private AsyncOperation operation;
    // 加載進度(由於加載進度不能為 1,所以需要此變量在加載進度大於某一個值時讓加載進度變為1)
    private float targetValue;

    void Start ()
    {
        // 初始化進度條
        loadingSlider.value = 0.0f;

        if (SceneManager.GetActiveScene ().name == "NowSence") {
            // 啟動協程
            StartCoroutine (AsyncLoading ());
        }
    }

    void Update ()
    {
        // operation.progress 加載進度
        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 * SliderLoadSpeed);
            // 避免插值運算一直進行
            if (Mathf.Abs (loadingSlider.value - targetValue) < 0.01f) {
                loadingSlider.value = targetValue;
            }
        }
        // 顯示加載百分比
        loadingText.text = ((int)(loadingSlider.value * 100)).ToString () + "%";

        // 當進度條完成 100% 時,加載場景
        if ((int)(loadingSlider.value * 100) == 100) {
            //允許異步加載完畢后自動切換場景
            operation.allowSceneActivation = true;
        }
    }

    // 加載場景的協程
    IEnumerator AsyncLoading ()
    {
        // 異步加載場景
        operation = SceneManager.LoadSceneAsync ("LoadSence");
        // 阻止當加載完成自動切換
        operation.allowSceneActivation = false;

        yield return operation;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM