unity 異步跳轉進度

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Loading : MonoBehaviour {

    AsyncOperation async;
    int progress = 0;
    public Image fill;


    void Start () {
        
        StartCoroutine(loadScene());
    }

    public Text txt_test;
    void Update()
    {

        //progress = (int)(async.progress * 100);
        //txt_test.text = "當前進度:" + progress;


    }

    //void OnGUI()
    //{
    //    if (GUILayout.Button("跳轉廠房", GUILayout.Width(100)))
    //    {
    //        //SceneManager.LoadSceneAsync("Loading");
    //        Global.loadSceneName = "ELE";
    //        //isOn = true;
    //        StartCoroutine(loadScene());
    //    }
    //}

     IEnumerator LoadScene()
    {
        float toProgress = 0.9f;//爲了解決progress值只到0.9的問題,90%以後顯示該值
        yield return new WaitForEndOfFrame();
        AsyncOperation asyncOper = SceneManager.LoadSceneAsync("DH");//跳轉的場景
        asyncOper.allowSceneActivation = false;//是否允許場景激活,設爲true則激活已加載的場景
        
        while (!asyncOper.isDone)
        {
            txt_test.text = Mathf.FloorToInt(asyncOper.progress * 100) + "%";
            fill.fillAmount = asyncOper.progress;
            if (asyncOper.progress >= 0.9f)
            {
                toProgress+=0.001f;
                //防止顯示超過99%
                if (toProgress >= 0.99)
                    toProgress = 0.99f;

                txt_test.text = Mathf.FloorToInt(toProgress * 100) + "%";
                fill.fillAmount = toProgress;

                //顯示到99%時跳轉場景,這裏跳轉有延時,視場景而定是否需要,或改變比值
                //if (toProgress >= 0.99)
                asyncOper.allowSceneActivation = true;
                
            }
            yield return new WaitForEndOfFrame();
        }

       // if (asyncOper.isDone){
           //場景加載完畢
       // }

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章