Unity 异步加载场景(简单上手版)

首先附上需要用到的代码:

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

public class MyLevelManager : MonoBehaviour
{
    static string nextLevel;
    AsyncOperation async;
    public float tempprogress;
    public Slider slider;
    public Text text;
    // Start is called before the first frame update
    void Start()
    {
        tempprogress = 0;
        //这里我加载场景的名字叫Loading
        if (SceneManager.GetActiveScene().name == "Loading")
        {
            async = SceneManager.LoadSceneAsync(nextLevel);
            async.allowSceneActivation = false;
        }
    }

    public void LoadLoadingLevel(string nextLevelName)
    {
        nextLevel = nextLevelName;
        SceneManager.LoadScene("Loading");
    }
    // Update is called once per frame
    void Update()
    {
        if (text && slider)
        {
            //这里为了加载更加流畅对原加载条进行改进,变成伪进度条
            //可以对Time.deltaTime*num中的num数字进行调整,达到想要的加载速度
            tempprogress = Mathf.Lerp(tempprogress, async.progress, Time.deltaTime * 2);
            text.text = ((int)(tempprogress / 9 * 10 * 100)).ToString() + "%";
            slider.value = tempprogress / 9 * 10;
            if (tempprogress / 9 * 10 >= 0.995)
            {
                text.text = 100.ToString() + "%";
                slider.value = 1;
                async.allowSceneActivation = true;
            }
        }
    }
}

下面就是脚本的使用方法:

首先在场景中要有个UI按钮Button,比如我这里的 开始游戏 (这里的按钮我加了背景图)

 然后在该Button的Inspector窗口中进行如下设置,红色箭头所指地方填上需要异步加载到的场景

 然后在Loading(Loading是我建的一个加载的场景名)场景中进行如下设置

然后再进行如下设置(这里我把脚本挂载到Canvas,当然挂在其他地方也可以)

红色箭头部分记得把Slider和Text拖进去

 

这样就给要加载的场景做好异步加载啦!

猜你喜欢

转载自blog.csdn.net/weixin_61725823/article/details/124219090