【Unity】场景异步加载、卸载

场景异步加载、卸载:

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

public class SceneTest
{
    const float loadWaitTime = 2;

    public IEnumerator LoadSceneAsync(string sceneName)
    {
        Scene scene = SceneManager.GetSceneByName(sceneName);
        if (scene.isLoaded)
        {
            Debug.Log("Scene is loaded : " + sceneName);
            yield break;
        }

        //可在此显示Loading界面
        //如果用LoadSceneMode.Single方式加载,需要单独做一个Loading场景,用于切场景过渡
        //这里使用LoadSceneMode.Additive方式,所有的UI界面都在主场景,场景过渡时使用Loading界面即可
        UIManager.Instance.ShowPanel<UILoadPanel>(true);

        float startTime = Time.time;

        //选择场景加载方式
        //LoadSceneMode.Single会卸载掉之前的原有的场景,只保留新加载场景
        //LoadSceneMode.Additive,会在原有场景的基础上附加新场景
        AsyncOperation operation = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);

        //AsyncOperation.progress范围(0~1)
        //isDone为false时,最大加载到0.9就会暂停,直到isDone为true时才会继续加载剩余的0.9 - 1.0
        //只有allowSceneActivation = true,isDone才会在progress = 1.0后,值为true
        //作用是让场景不会在加载完成后自动跳转到下一个场景
        operation.allowSceneActivation = false;
        while (!operation.isDone)
        {
            //手动延长加载时间,防止加载界面展示时间过短
            if (Time.time - startTime >= loadWaitTime)
            {
                if (operation.progress >= 0.9f && !operation.allowSceneActivation)
                    operation.allowSceneActivation = true;
            }
            yield return null;
        }

        //如果不需要等待,可直接加载后跳转场景
        //operation.allowSceneActivation = true;
        //while (!operation.isDone)
        //{
        //    yield return null;
        //}

        //可在此关闭Loading界面
        UIManager.Instance.HideUICoroutine<UILoadPanel>();

        //加载完成,可以设置回调
        Debug.Log("LoadSceneAsync Success : " + sceneName);
    }

    // ----------

    public IEnumerator UnloadSceneAsync(string sceneName)
    {
        Scene scene = SceneManager.GetSceneByName(sceneName);

        if (!scene.isLoaded)
        {
            Debug.Log("Scene is not loaded : " + sceneName);
            yield break;
        }

        AsyncOperation async = SceneManager.UnloadSceneAsync(scene);
        yield return async;
    }
}

之前试过同步加载的方式:

比如:从主场景切换到战斗场景,战斗场景初始为空场景,仅挂载加载脚本,场景内的资源都采用协程动态加载的方式 ,因为同步加载空场景很快,不会长时间卡在某一帧,只要处理好资源的动态加载,也可以尝试同步加载,这可以避免Loading界面,体验更流畅。

发布了104 篇原创文章 · 获赞 74 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_39108767/article/details/102700642