【unity】加載場景進度條

在遊戲中切換場景是很有用處的,尤其是大場景,加載時間很長,我們可以顯示一個進度條異步加載,提高用戶體驗

1.新建場景

新建兩個場景,分別是“LoadScene”和“NewScene”,其中LoadScene用來顯示進度條
新建好之後,我們分別點擊“File–Build Setting–Add Open Scenes”添加場景

2.創建進度條

我們打開LoadScene,依次點擊“GameObject–UI–Slider”創建一個進度條,修改好大小和位置,再創建一個Text用於顯示進度信息
在這裏插入圖片描述

3.創建腳本

新建一個腳本,比如叫LoadScene.cs,內容如下

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

public class LoadScene : MonoBehaviour
{
    AsyncOperation async;
    public Slider slider;
    public Text text;//百分制顯示進度加載情況

    void Start()
    {
        //開啓協程
        StartCoroutine("loginMy");
    }

    void Update()
    {

    }
    IEnumerator loginMy()
    {
        int displayProgress = 0;
        int toProgress = 0;
        AsyncOperation op = SceneManager.LoadSceneAsync("NewScene"); //此處改成要加載的場景名
        op.allowSceneActivation = false;
        while (op.progress < 0.9f) //此處如果是 <= 0.9f 則會出現死循環所以必須小0.9
        {
            toProgress = (int)op.progress * 100;
            while (displayProgress < toProgress)
            {
                ++displayProgress;
                SetLoadingPercentage(displayProgress);
                yield return new WaitForEndOfFrame();//ui渲染完成之後
            }
        }
        toProgress = 100;
        while (displayProgress < toProgress)
        {
            ++displayProgress;
            SetLoadingPercentage(displayProgress);
            yield return new WaitForEndOfFrame();
        }
        op.allowSceneActivation = true;

    }

    private void SetLoadingPercentage(int displayProgress)
    {
        slider.value = displayProgress;
        text.text = displayProgress.ToString() + "%";
    }
}

4.賦值

回到LoadScene,我們把上面的腳本賦值給一個場景的物體,比如說MainCamera,然後把之前創建的Slider和Text拖動賦值給腳本,再運行LoadScene場景就能看到進度條了
在這裏插入圖片描述

5.燈光問題

如果使用上面的方法進行切換場景,會發現NewScene的光線會暗黃,解決方法
依次點擊“Window–lighting–Settings”,取消“Auto Generate”,然後點擊“Generate Lighting”就行

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