【Unity】AssetBundle加载与卸载

unity官方apiAssetBundle-LoadFromFileAsync - Unity 脚本 API

异步加载AB包

复制代码
using UnityEngine;
using System.Collections;
using System.IO;

public class LoadFromFileAsyncExample : MonoBehaviour
{
    IEnumerator Start()
    {
        var bundleLoadRequest = AssetBundle.LoadFromFileAsync(Path.Combine(Application.streamingAssetsPath, "myassetBundle"));
        yield return bundleLoadRequest;

        var myLoadedAssetBundle = bundleLoadRequest.assetBundle;
        if (myLoadedAssetBundle == null)
        {
            Debug.Log("Failed to load AssetBundle!");
            yield break;
        }

        var assetLoadRequest = myLoadedAssetBundle.LoadAssetAsync<GameObject>("MyObject");
        yield return assetLoadRequest;

        GameObject prefab = assetLoadRequest.asset as GameObject;
        Instantiate(prefab);

        myLoadedAssetBundle.Unload(false);
    }
}

需要注意的是同一个ab包一次只能加载一个,不可以同时加载,

报错:The AssetBundle 'xxxxx' can't be loaded because another AssetBundle with the same files is already loaded.

如果AB包已经加载过则先进行卸载:

复制代码
        if (myLoadedAssetBundle != null)
        {
            myLoadedAssetBundle.Unload(false);//关键代码
        }

卸载AB包

1、卸载全部的目前没有使用的资源: Resources.UnloadUnusedAssets()

2、卸载 AssetBundle 释放其数据: AssetBundle.Unload(true/false);

3、卸载当前已加载的所有 AssetBundle: AssetBundle.UnloadAllAssetBundles(true/false)

当 为 false 时,将释放当前加载的捆绑包中的压缩文件数据,但已从捆绑包中加载的任何对象实例将保持不变。

UnloadAllAssetBundles不会中断异步加载过程,如果已经在进行异步加载了此时调用AssetBundle.UnloadAllAssetBundles,那么这个AB包还是会加载出来。

复制代码
using UnityEngine;
 
public class AssetBundleManager : MonoBehaviour
{
    public void LoadAssetBundle(string bundleName)
    {
        AssetBundle bundle = AssetBundle.LoadFromFile(bundleName);
        if (bundle != null)
        {
            // 假设你有一个你想要加载的资源的名字
            string assetName = "myAsset";
            UnityEngine.Object asset = bundle.LoadAsset(assetName);
            // 使用 asset ...
 
            // 卸载AssetBundle
            bundle.Unload(false);
 
            // 如果确定没有其他引用,可以进一步释放内存
            Resources.UnloadUnusedAssets();
            System.GC.Collect();
        }
    }
}
相关推荐
LONGZETECH15 分钟前
新能源汽车充电设备装配与调试仿真教学软件 技术架构与核心实现解析
大数据·算法·3d·unity·架构·汽车
丁小未1 小时前
Unity 几种常见合批手段的要求
游戏·unity·合批·srpbatcher·动态合批·静态合批
旧物有情20 小时前
游戏开发常用架构 #MVP,MVC
游戏·unity·架构·mvc
勇踏前人未索之境1 天前
Unity打包运行于鸿蒙手机
unity·智能手机·harmonyos
玖玥拾1 天前
Unity 3D 笔记(十一)UI 框架进阶:栈弹窗交互、BasePanel 基类虚方法、DoTween 界面动画
笔记·3d·unity
郝学胜-神的一滴1 天前
中级OpenGL教程 023:Assimp模型加载全解——从源码到架构的骈文探秘
c++·unity·游戏引擎·cmake·unreal engine·opengl
xcLeigh2 天前
Unity基础:GameObject与Component——Unity核心架构思想彻底理解
unity·教程·component·gameobject
郝学胜-神的一滴2 天前
中级OpenGL教程 022:探秘三维世界的血脉传承——物体父子关系与矩阵递归奥义
c++·线性代数·unity·矩阵·游戏引擎·unreal engine·opengl
weixin_424294673 天前
Unity的测试Edit Mode和Play Mode,有什么区别?
unity