Unity AssetBundle打包、加载、卸载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36718838/article/details/82383463

 AssetBundle打包

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);//平台
    }

}
None Build assetBundle without any special option.(LAMA压缩,压缩率高,解压久)
UncompressedAssetBundle Don'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。

猜你喜欢

转载自blog.csdn.net/qq_36718838/article/details/82383463