【Unity筆記】使用協程(Coroutine)異步加載場景


using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using System;

public class LoadingPage : MonoBehaviour {

    public UISlider progressBar;

    // 目標進度
    float target = 0;
    // 讀取場景的進度,取值范圍0~1
    float progress = 0;
    // 異步對象
    AsyncOperation op = null;

    void Start () {
        Debug.Log("開始LoadScene");

        op = SceneManager.LoadSceneAsync("GamePlayScene");
        op.allowSceneActivation = false;
        progressBar.value = 0;

        // 開啟協程,開始調用加載方法
        StartCoroutine(processLoading());
    }

    float dtimer = 0;
    void Update()
    {
        progressBar.value = Mathf.Lerp(progressBar.value, target, dtimer * 0.02f);
        dtimer += Time.deltaTime;
        if (progressBar.value > 0.99f)
        {
            progressBar.value = 1;
            op.allowSceneActivation = true;
        }
    }

    // 加載進度
    IEnumerator processLoading()
    {
        while (true)
        {
            target = op.progress; // 進度條取值范圍0~1
            if (target >= 0.9f)
            {
                target = 1;
                yield break;
            }
            yield return 0;
        }
    }

}

 


免責聲明!

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



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