Unity异步加载

该代码示例展示了在Unity引擎中如何创建一个SceneController类来管理场景的异步加载。SceneController类包含了一个加载进度变量和一个协程,用于平滑地更新加载进度,并在加载完成后触发回调函数。通过调用LoadScene方法,可以启动场景加载过程,同时允许自定义加载完成后的回调。
摘要由CSDN通过智能技术生成
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Universal
{
    public class SceneController : MonoBehaviour
    {
        public static SceneController Instance;

        private int displayProgress;
        public AsyncOperation asyncOperation;
        private Coroutine loadCoroutine;

        public bool loading = true;

        void Start()
        {
            Instance = this;
        }

        //加载场景
        public void LoadScene(string sceneName, Action OnSceneLoaded = null)
        {
            if (loadCoroutine == null)
            {
                loadCoroutine = StartCoroutine(DoLoadScene(sceneName, OnSceneLoaded));
            }
        }

        public IEnumerator DoLoadScene(string sceneName, Action OnSceneLoaded)
        {
            loading = true;
            displayProgress = 0;
            int toProgress = 0;

            asyncOperation = SceneManager.LoadSceneAsync(sceneName);
            asyncOperation.allowSceneActivation = false;
            while (asyncOperation.progress < 0.9f)
            {
                toProgress = (int)asyncOperation.progress * 100;
                while (displayProgress < toProgress)
                {
                    ++displayProgress;
                    //SetLoadingPercentage(displayProgress);
                    yield return new WaitForEndOfFrame();
                }
            }
            toProgress = 100;
            while (displayProgress < toProgress)
            {
                ++displayProgress;
                //SetLoadingPercentage(displayProgress);
                yield return new WaitForEndOfFrame();
            }
            //asyncOperation.allowSceneActivation = true;
            loadCoroutine = null;
            if (OnSceneLoaded != null)
            {
                OnSceneLoaded();
            }
            loading = false;
        }

        //public void SetLoadingPercentage(int DisplayProgress)
        //{
        //    m_Slider.value = DisplayProgress * 0.01f;
        //    m_Text.text = DisplayProgress.ToString() + "%";
        //}
    }
}

使用示例:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值