Unity 场景异步加载

首先如下图把相关场景加入到Build Settings

Loading 脚本内容如下:

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

public class Loading : MonoBehaviour
{
    public string SceneName;
    private Text txt_Progress;
    private AsyncOperation ao;
    private bool isLoad = false;
 
    private void Awake()
    {
        txt_Progress = GetComponent<Text>();
     
        txt_Progress.text = "";
        GameObject.Find("btn_Start").GetComponent<Button>().onClick.AddListener(() =>
        {
            StartLoad();
        });
    }
 
    private void StartLoad()//开始加载
    {
        gameObject.SetActive(true);
        StartCoroutine("Load");//开启加载协程,为什么有引号,因为必须有引号,协程才能关闭停止
    }
    IEnumerator Load()//协程加载
    {
        int displayProgress = -1;
        int toProgress = 100;

        while (displayProgress < toProgress)//加载过程中执行
        {
            ++displayProgress;
            ShowProgress(displayProgress);//显示加载进度

            if (isLoad == false)
            {
                ao = SceneManager.LoadSceneAsync(SceneName);//异步加载,返回值是AsyncOperation,是异步进程
                ao.allowSceneActivation = false;//是否允许场景激活,加载进度没有达到100,则一直显示加载场景
                isLoad = true;//防止多次加载
            }
            yield return new WaitForEndOfFrame();//每执行一次While之后等待一下,等待这一帧的结束
        }
        if (displayProgress == 100)
        {
            ao.allowSceneActivation = true;//当被加载到100之后,激活被加载的场景
            StopCoroutine("Load");//停止协程
        }
    }
    private void ShowProgress(int progress)
    {
        txt_Progress.text = progress.ToString() + "%";
    }
}

详细教程请见:http://www.sikiedu.com/course/306/task/16503/show

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋斗的菇凉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值