【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();
        }
    }
}
相关推荐
ellis19709 小时前
toLua[六] Examples 05_LuaCoroutine分析
unity
程序员正茂19 小时前
Unity3d中Tab控件的实现
ui·unity·tab·控件
三掌柜6661 天前
突破AR视觉交互边界:Unity赋能Rokid AR眼镜实现高精度图像识别与实时跟踪
unity·ar·交互
Brianna Home2 天前
Godot4.3开发2D游戏全记录
游戏·游戏引擎·godot·游戏程序·动画
王维志2 天前
使用Asp.Net WebApi(.net 8)托管Unity WebGL
unity·游戏引擎·webgl
开发游戏的老王2 天前
虚幻引擎入门教程:虚幻引擎的安装
游戏引擎·虚幻
muyouking112 天前
Unreal Engine 中的旋转表示:FQuat 与 FRotator 全面解析
游戏引擎·虚幻
lrh30253 天前
Custom SRP 12 - HDR
3d·unity·srp·render pipeline
霜绛3 天前
Unity:Json笔记——Json文件格式、JsonUtlity序列化和反序列化
学习·unity·json·游戏引擎
开发游戏的老王3 天前
虚幻引擎虚拟制片入门教程 之 创建项目及启用插件
游戏引擎·虚幻