【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();
        }
    }
}
相关推荐
敲代码的 蜡笔小新4 小时前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
敲代码的 蜡笔小新7 小时前
【行为型之解释器模式】游戏开发实战——Unity动态公式解析与脚本系统的架构奥秘
unity·设计模式·游戏引擎·解释器模式
Magnum Lehar10 小时前
3d游戏引擎的Utilities模块实现
c++·算法·游戏引擎
敲代码的 蜡笔小新11 小时前
【行为型之观察者模式】游戏开发实战——Unity事件驱动架构的核心实现策略
观察者模式·unity·设计模式·c#
向宇it11 小时前
【unity游戏开发——编辑器扩展】使用EditorGUI的EditorGUILayout绘制工具类在自定义编辑器窗口绘制各种UI控件
开发语言·ui·unity·c#·编辑器·游戏引擎
qq_2052790515 小时前
unity 鼠标更换指定图标
unity·游戏引擎
虾球xz15 小时前
游戏引擎学习第279天:将实体存储移入世界区块
c++·学习·游戏引擎
虾球xz17 小时前
游戏引擎学习第278天:将实体存储移入世界区块
数据库·c++·学习·游戏引擎
FAREWELL0007517 小时前
Unity基础学习(九)输入系统全解析:鼠标、键盘与轴控制
学习·unity·c#·游戏引擎
敲代码的 蜡笔小新21 小时前
【行为型之策略模式】游戏开发实战——Unity灵活算法架构的核心实现策略
unity·设计模式·c#·策略模式