Unity AssetBundle打包、加载、卸载

 AssetBundle打包

1.在资源的AssetLabel,设置资源的BundleName以及BundleVariant,然后进行打包。

BuildAssetBundles的时候自动收集打AB。

AssetBundleManifest BuildAssetBundles(string outputPath, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);

2.定义AssetBundleBuild[]数组,只打包这些资源,但需要注意的是也要打包依赖项。

AssetBundleManifest BuildAssetBundles(string outputPath, AssetBundleBuild[] builds, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);

using UnityEditor;
using System.IO;
public class CreateAssetBundles //进行AssetBundle打包
{
    [MenuItem("Assets/Build AssetBundles")]
    static void BuildAllAssetBundles()
    {
        string dir = "AssetBundles";
        if (Directory.Exists(dir) == false)
        {
            Directory.CreateDirectory(dir);
        }
        BuildPipeline.BuildAssetBundles(dir, //路径必须创建
            BuildAssetBundleOptions.ChunkBasedCompression, //压缩类型
            BuildTarget.StandaloneWindows64);//平台
    }

}
NoneBuild assetBundle without any special option.(LAMA压缩,压缩率高,解压久)
UncompressedAssetBundleDon't compress the data when creating the asset bundle.(不压缩,解压快)
ChunkBasedCompression

Use chunk-based LZ4 compression when creating the AssetBundle.

(压缩率比LZMA低,解压速度接近无压缩)

AssetBundle加载

1.LoadFromMemory(LoadFromMemoryAsync)

2.LoadFromFile(LoadFromFileAsync)

3.UnityWebRequest

第一种

IEnumerator Start()
{
    string path = "AssetBundles/wall.unity3d";
    AssetBundleCreateRequest request = 
                            AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
    yield return request;

    AssetBundle ab = request.assetBundle;
    GameObject wallPrefab = ab.LoadAsset<GameObject>("Cube");
    Instantiate(wallPrefab);
}

第二种

IEnumerator Start()
{
    string path = "AssetBundles/wall.unity3d";
    AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
    yield return request;
    AssetBundle ab = request.assetBundle;
    GameObject wallPrefab = ab.LoadAsset<GameObject>("Cube");
    Instantiate(wallPrefab);
}

第三种

IEnumerator Start()
{
    string uri = @"http://localhost/AssetBundles/cubewall.unity3d";
    UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri);
    yield return request.Send();
    AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
    GameObject wallPrefab = ab.LoadAsset<GameObject>("Cube");
    Instantiate(wallPrefab);
}

AssetBundle卸载

AssetBundle.Unload(bool),T

true卸载所有资源 

false只卸载没使用的资源,而正在使用的资源与AssetBundle依赖关系会丢失,调用Resources.UnloadUnusedAssets可以卸载。或者等场景切换的时候自动调用Resources.UnloadUnusedAssets。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值