【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();
        }
    }
}
相关推荐
程序猿多布6 小时前
预定义委托(C# and Unity)
unity·c#
虾球xz9 小时前
游戏引擎学习第108天
学习·游戏引擎
虾球xz10 小时前
游戏引擎学习第112天
java·学习·游戏引擎
Edision_li16 小时前
DeepSeek教unity------Dotween
unity·游戏引擎
zfoo-framework17 小时前
Unity中NavMesh的使用 及其 导出给java服务端进行寻路
unity
程序猿多布17 小时前
数学函数(C#、Lua 、Unity)
unity·c#·lua
虾球xz19 小时前
游戏引擎学习第110天
数码相机·学习·游戏引擎
爱写代码的山山1 天前
虚幻蓝图解决抗锯齿方案
游戏·ue5·游戏引擎·虚幻·抗锯齿化
github_czy1 天前
(9/100)每日小游戏平台系列
javascript·python·游戏引擎·游戏程序
头发掉光的程序员1 天前
正顺基碱基
c++·算法·游戏引擎·图形渲染