【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();
        }
    }
}
相关推荐
T.D.C5 小时前
【业务框架】3C-相机-Cinemachine
unity
一线灵11 小时前
跨平台游戏引擎 Axmol-2.6.1 发布
游戏引擎
Clank的游戏栈16 小时前
Unity基于GraphView的可视化关卡编辑器开发指南
unity·编辑器·游戏引擎
海尔辛1 天前
Unity UI 性能优化--Sprite 篇
ui·unity·性能优化
三巧1 天前
Godot 敌人生成半径和围墙不匹配,导致敌人错误的生成在围墙外的解决代码
游戏引擎·godot
技术小甜甜1 天前
【Godot引擎】如何使用内置的全局搜索功能提升开发效率
游戏引擎·godot
技术小甜甜1 天前
【Godot】如何导出 Release 版本的安卓项目
android·游戏引擎·godot
XR-AI-JK2 天前
Unity VR/MR开发-VR设备与适用场景分析
unity·vr·mr
ChiLi_Lin2 天前
Unity异常上报飞书工具
unity·游戏引擎·飞书
Magnum Lehar2 天前
vulkan游戏引擎的makefile启动环境实现
游戏引擎