1. 程式人生 > >Unity AssetBundle打包、載入、解除安裝

Unity AssetBundle打包、載入、解除安裝

 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壓縮,壓縮率高,解壓久)
Don't compress the data when creating the asset bundle.(不壓縮,解壓快)

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。