Unity makes scene loading progress bar (asynchronous scene loading)

1. Create a loading UI

  1. Create a new Panel, adjust the color to dark gray, and opacity 255

  2. Create a new Slider under the Panel and adjust the Slider; create a new Text under the Panel to display the percentage of the progress bar

  3. Create a new empty GameObject and name it LoadManagerGameObject

  4. Create a new script LoadManager.cs, drag and drop the script onto the LoadManagerGameObject,
    insert image description here

  5. Uncheck the enabled of the Panel
    insert image description here

  6. Create a new Button and name it Next Level; OnClick() click +, drag the LoadManagerGameObject in the Hierarchy to the Object, and select the function LoadNextLevel()
    insert image description here
    insert image description here

  7. File-Build Settings, drag the current scene and the scene to be loaded into the window
    insert image description here

  8. LoadManager.cs

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

public class LoadManager : MonoBehaviour
{
    
    
    public GameObject loadScreen;
    public Slider slider;
    public Text text;

    public void LoadNextLevel()
    {
    
    
        StartCoroutine(LoadLevel());//开启协程
    }

    IEnumerator LoadLevel()
    {
    
    
        loadScreen.SetActive(true);//可以加载场景
        AsyncOperation operation = SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex + 1);

        operation.allowSceneActivation = false;//不允许场景自动跳转
        while(!operation.isDone)//场景加载没有完成时
        {
    
    
            slider.value = operation.progress;//slider的值=加载的进度值
            text.text = operation.progress * 100 + "%";

            if (operation.progress >= 0.9F)
            {
    
    
                slider.value = 1.0f;
                text.text = "100%";
                operation.allowSceneActivation = true;//允许场景自动跳转
            }

            yield return null;//跳出协程
        }
    }
}

Secondary directory

Third-level directory

AsyncOperation
LoadManager

Guess you like

Origin blog.csdn.net/weixin_45686837/article/details/123088250