Unity异步加载进度条
阅读原文时间:2023年07月11日阅读:1

先上代码:

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

#region 佛祖保佑
/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            佛祖保佑       永无BUG
*/
#endregion

public class AsyncLoadScene : MonoBehaviour
{
    public static string NEXTSCENENAME = "ChooseLevelScene";
    private Text text_loadProgress;
    private RectTransform rectTransform_progressBar;
    private AsyncOperation asyncLoadScene;
    private float progressValue;

    private void Start()
    {
        text_loadProgress = transform.Find("Text").GetComponent<Text>();
        rectTransform_progressBar = transform.Find("Image").GetComponent<RectTransform>();

        asyncLoadScene = SceneManager.LoadSceneAsync(NEXTSCENENAME);
        asyncLoadScene.allowSceneActivation = false;
    }

    private void Update()
    {
        if(text_loadProgress && rectTransform_progressBar)
        {
            progressValue = Mathf.Lerp(progressValue, asyncLoadScene.progress / 0.9F, Time.deltaTime);
            text_loadProgress.text = (progressValue * 100F).ToString("F0") + "%";
            rectTransform_progressBar.sizeDelta = new Vector2(progressValue * 1280F, 85F);

            if(rectTransform_progressBar.sizeDelta.x > 1275F) asyncLoadScene.allowSceneActivation = true;
        }
    }
}

接着如果你感到迷惑,请看如下游戏对象层级:

脚本挂在Panel对象上

那如何使用她呢?

public GameObject Prefab_loadScene;

private void Click_play(){
    Instantiate(Prefab_loadScene);
}
//--------------或者请看如下----------------
public GameObject Prefab_loadScene;

private void Click_play(){  AsyncLoadScene.NEXTSCENENAME = "MainScene";  GameObject loadScener = Instantiate(Prefab_loadScene);

}