Unity assetbundle筆記
一:AssetBundle使用流程:
1.給指定資源設定assetbundle屬性
2.構建assetbundle包(打ab包),也可以用ab瀏覽工具打包
BuildPipeline.BuildAssetBundles(目錄,BuildAssetBundleOptions,BuildTarget);//除了在指定目錄下生成ab包,還會自動在目錄下生成與資料夾同名的ab包,以及Manifest檔案,可用來載入依賴關係
3.上傳AB包到伺服器
4.載入AB包,和包中資源(載入:資源將會儲存到裝置執行記憶體中)
AssetBundle ab = AssetBundle.LoadFormFile("ab包相對路徑,要寫出ab包字尾");//load到記憶體中 GameObject go = ab.LoadAsset<GameObject>("prefab名字"); Instantiate(go);
二:ab包分組策略:
1.把經常更新的資源放在單獨的包裡,跟不常更新的資源分開
2.把需要同時載入的資源放在一個包裡
3.把其他包所共享的資源放在一個包裡,比如場景的shader,mat(需要用到依賴打包)
4.把一些需要同時載入的小資源放在一個包裡
5.如果同一個資源有兩個版本,可以通過後綴來區分
三:依賴打包:
1.unity自動會載入依賴的資源,比如模型共享的材質,直接把材質資源打包,模型打包後文件變小,而且會自動載入所依賴的資源。
2.依賴的資訊在Manifest檔案中
3.ab包有依賴關係時,必須載入被依賴的ab包。
四:API講解(©SIKI)
1.打ab包的API
2.載入ab包的API:
3.LoadFormMemory()
IEnumerator Start(){//非同步載入 AssetBundleCreateRequest request = AssetBundle.LoadFormMemoryAsync( File.ReadAllBytes("資源路徑")); yield return request; AssetBundle ab = request.assetBundle; } void Start( ){//同步載入 AssetBundle ab = AssetBundle.LoadFormMemory(File.ReadAllBytes("路徑")); }
4.LoadFormFile()
IEnumerator Start(){//非同步載入 AssetBundleRequest request = AssetBundle.LoadFormFileAsync("包路徑"); yield return request; AssetBundle ab = request.assetBundle; } void Start(){//同步載入 AssetBundle ab = AssetBundle.LoadFormFile("包路徑"); }
5.UnityWebRequest
using UnityEngine.NetWorking IEnumator Start(){
//本地地址 string url = @"file:///E:\路徑名字\xxx.assetBundle";
//遠端地址
string url2 = @"http://www.域名.com/路徑名稱/xxx.assetBundle";
UnityWebRequest request = UnityWebRequest.GetAssetBundle(url); yield return request.Send();//傳送請求並等待下載完成 //載入方式一 AssetBundle ab = DownLoadHandlerAssetBundle.GetContent(request); //載入方式二 AssetBundle ab = (request.downLoadHandler as DownLoadHandlerAssetBundle).assetBundle; }
6.載入ab包中的資源:
T objectFromBundle = bundleObject.LoadAsset<T>(assetName);//載入一個資源 Unity.Object[] objectArray = loadedAssetBundle.LoadAllAssets();//載入所有資源
五:載入Manifest檔案,並讀取依賴包
AssetBundle assetBundle = AssetBundle.LoadFromFile(manifestFilePath);//注意這裡的manifestFilePath是指自動生成的,與資料夾同名的那個ab檔案。不是manifest檔案!!臭老外文件瞎幾把亂寫 AssetBundleManifest manifest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); string[] dependencies = manifest.GetAllDependencies("xxx.assetBundle"); //引數是ab檔案全名 foreach(string dependency in dependencies) { AssetBundle.LoadFromFile(Path.Combine(assetBundlePath, dependency)); }
六:解除安裝記憶體中的ab包
1.AssetBundle.Unload(bool);
2.true:全部解除安裝,會造成資源引用丟失
3.false:在使用中asset不會解除安裝,會造成記憶體浪費
4.使用Resource.UnloadUnusedAssets()解除安裝記憶體中沒被使用的個別asset(比如材質,貼圖等等)
5.正確的解除安裝方法:場景切換的時候Unload(false)部分解除安裝,U3D自動呼叫Resource.UnloadUnusedAssets(),之後再手動呼叫一次確保記憶體沒有浪費
七:TIPS
1.sprite2d型別的資源最後會根據packing tag打包到不同的圖集(sprite atlas)中,推薦相同圖集裡的圖片打包到一個ab包裡
2.UnityAssetBundle Broswer Tool 外掛