原創(chuàng)文章如需轉(zhuǎn)載請注明:轉(zhuǎn)載自風(fēng)宇沖Unity3D教程學(xué)院
AssetBundles第一講:基本使用AssetBundles是從unity導(dǎo)出你選擇的assets,它使用特有的壓縮格式并且應(yīng)用可以實(shí)時去讀取它。包括模型貼圖音頻等任何asset類型,甚至整個場景。壓縮大小基本能達(dá)到zip的效果。AssetBundles從設(shè)計時就定位為可以很簡單就下載到應(yīng)用里。如果你想包括自定義的binary數(shù)據(jù),就要用.bytes后綴,Unity將作為TextAssets導(dǎo)入他們。
注意:AssetBundles并不像Unity官方說的那樣,各種unity版本兼容。經(jīng)測試在unity4中創(chuàng)建的ab,在4中正常使用,但在3.5.0里無法正常使用。說明用AB不能向下兼容。
開發(fā)階段:
(1)創(chuàng)建AssetBundles:
不能是 sceneobjects的objects使用BuildPipeline.BuildAssetBundletargetplatform要指定,不能用默認(rèn)參數(shù),默認(rèn)模式是webplayer
- usingUnityEngine;
- usingUnityEditor;
- publicclassExportAssetBundles{
- [MenuItem("Assets/BuildAssetBundle From Selection - Track dependencies")]
- staticvoidExportResource() {
- // Bring up save panel
- stringpath=EditorUtility.SaveFilePanel ("SaveResource","","NewResource","unity3d");
- if(path.Length!=0) {
- // Build the resource file fromthe active selection.
- Object[] selection=Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
- BuildPipeline.BuildAssetBundle(Selection.activeObject,selection,
- path,BuildAssetBundleOptions.CollectDependencies|BuildAssetBundleOptions.CompleteAssets
- ,BuildTarget.StandaloneWindows);
- Selection.objects =selection;
- }
- }
- [MenuItem("Assets/BuildAssetBundle From Selection - No dependency tracking")]
- staticvoidExportResourceNoTrack() {
- // Bring up save panel
- stringpath=EditorUtility.SaveFilePanel ("SaveResource","","NewResource","unity3d");
- if(path.Length!=0) {
- // Build the resource file fromthe active selection.
- BuildPipeline.BuildAssetBundle(Selection.activeObject,Selection.objects,path);
- }
- }
- }
創(chuàng)建bundle并自定義名稱。assetName的長度及排列與assets對應(yīng)。并不是真正改變物體的名稱,只是在assetBundle.Load的時候有個唯一對應(yīng)的名稱
對上面代碼僅需修改第11行。將BuildPipeline.BuildAssetBundle(Selection.activeObject,selection,
path,BuildAssetBundleOptions.CollectDependencies|BuildAssetBundleOptions.CompleteAssets
,BuildTarget.StandaloneWindows);里的第一個參數(shù)mainAsset去掉,并在selection也就是Object[]之后加string[]assetName即可
- [MenuItem("Assets/BuildAssetBundle From Selection Names- Trackdependencies")]
- staticvoidExportResourceWithNames() {
- // Bring up savepanel
- stringpath=EditorUtility.SaveFilePanel("SaveResource","","NewResource","unity3d");
- if(path.Length!=0) {
- // Build the resourcefile from the active selection.
- Object[] selection=Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
- string[] names=newstring[selection.Length];
- for(inti=0;i
- {
- names[i] =i+"_"+selection[i].name;
- }
- BuildPipeline.BuildAssetBundleExplicitAssetNames(selection,names,
- path,BuildAssetBundleOptions.CollectDependencies|BuildAssetBundleOptions.CompleteAssets
- ,BuildTarget.StandaloneWindows);
- Selection.objects= selection;
- }
- }
- usingSystem;
- usingSystem.IO;
- usingUnityEngine;
- publicclassLoadAssetBundle:MonoBehaviour{
- privateAssetBundleassetBundle;
- privateAssetBundleCreateRequestrequest;
- voidUpdate () {
- }
- voidOnGUI()
- {
- if(GUI.Button(newRect(0,0,100,50),"Load"))
- {
- byte[] bs =File.ReadAllBytes(Application.dataPath+"/withNames.unity3d");
- request=AssetBundle.CreateFromMemory(bs);
- }
- if(GUI.Button(newRect(0,50,100,50),"Check"))
- {
- if(request.isDone==true)
- {
- assetBundle = request.assetBundle;
- UnityEngine.Objectobj =assetBundle.Load("0_Cube");
- Instantiate(obj);
- }
- }
- }
- usingUnityEngine;
- usingUnityEditor;
- public classBuildScene:MonoBehaviour{
- [MenuItem("Build/BuildWebplayerStreamed")]
- staticvoidBuildScenes()
- {
- string[] levels=newstring[1];
- levels[0] ="Assets/scene.unity";
- BuildPipeline.BuildStreamedSceneAssetBundle(levels,"Assets/myLevel.unity3d",BuildTarget.StandaloneOSXIntel);
- }
- }
兼容性
| Platform compatibility forAssetBundles | |||||
| Standalone | Webplayer | iOS | Android | ||
| Editor | Y | Y | Y | Y | |
| Standalone | Y | Y | |||
| Webplayer | Y | Y | |||
| iOS | Y | ||||
| Android | Y | ||||
(2)上傳AssetBundles: 基于你所使用的服務(wù)器決定如何上傳。
使用階段:
(1)下載AssetBundles:
1AssetBundle.CreateFromFile:(1)只能用于pc和macstandalone(2)只支持Uncompressed:也就是在build的時候buildoption還要加上UncompressedAssetBundle。(3)必須得是絕對路徑。 AssetBundleassetBundle =AssetBundle.CreateFromFile("D:/myBundle4.unity3d");
2AssetBundle.CreateFromMemory(bs);
- using System;
- using System.IO;
- using UnityEngine;
- public class LoadAssetBundle : MonoBehaviour {
- privateAssetBundle assetBundle;
- privateAssetBundleCreateRequest request;
- voidUpdate () {
- if(request!=null)
- print(request.progress);
- }
- voidOnGUI()
- {
- if(GUI.Button(new Rect(0,0,100,50),"Load"))
- {
- byte[] bs =File.ReadAllBytes("D:/myBundle.unity3d");
- request =AssetBundle.CreateFromMemory(bs);
- }
- if(GUI.Button(new Rect(0,50,100,50),"Check"))
- {
- if(request.isDone == true)
- {
- print("name:"+request.assetBundle.mainAsset.name);
- Instantiate(request.assetBundle.mainAsset);
- }
- }
- }
- }
3 AssetBundle bundle = www.assetBundle;注:WWW也是可以讀取本地文件的,只需要在路徑前file://即可,如WWW myWWW = new WWW("file://E://LSY/wamp/www/cat.jpg");
- using System;
- using System.IO;
- using UnityEngine;
- using System.Collections;
- public class LoadAssetBundle : MonoBehaviour {
- privateAssetBundle assetBundle;
- privatestring address ="http://127.0.0.1/AssetBundles/myBundle.unity3d";
- voidOnGUI()
- {
- if(GUI.Button(new Rect(0,0,100,50),"Load web"))
- {
- StartCoroutine(Load());
- }
- }
- IEnumerator Load() {
- // Download the file from theURL. It will not be saved in the Cache
- stringAssetName="";
- WWW www = newWWW(address);
- yield return www;
- if (www.error != null)
- throw new Exception("WWWdownload had an error:" + www.error);
- AssetBundle bundle =www.assetBundle;
- if (AssetName == "")
- Instantiate(bundle.mainAsset);
- else
- Instantiate(bundle.Load(AssetName));
- // Unload the AssetBundles compressed contents to conservememory
- bundle.Unload(false);
- }
- }
下載過程中可以更換下載地址,并保證版本一致, Webplayer的cache限制在50MB以內(nèi)。
與普通的www下載僅僅是一句代碼的區(qū)別
WWW www = new WWW(address);
WWW www =WWW.LoadFromCacheOrDownload(address,1);
- using System;
- using System.IO;
- using UnityEngine;
- using System.Collections;
- public class LoadAssetBundle : MonoBehaviour {
- privateAssetBundle assetBundle;
- privatestring address ="http://127.0.0.1/AssetBundles/myBundle.unity3d";
- voidOnGUI()
- {
- if(GUI.Button(new Rect(0,0,100,50),"Load web"))
- {
- StartCoroutine(Load());
- }
- }
- IEnumerator Load() {
- stringAssetName="";
- WWW www =WWW.LoadFromCacheOrDownload(address,1);
- yield return www;
- if (www.error != null)
- throw new Exception("WWWdownload had an error:" + www.error);
- AssetBundle bundle =www.assetBundle;
- if (AssetName == "")
- Instantiate(bundle.mainAsset);
- else
- Instantiate(bundle.Load(AssetName));
- // Unload the AssetBundles compressed contents to conservememory
- bundle.Unload(false);
- }
- }
(2)使用AssetBundles里的資源:
bool AssetBundle.Contains(string name)bundle中是否含有名為name的asset
Object AssetBundle.Load(string name) 讀取bundle中名稱為name的asset
Object AssetBundle.LoadAll()
UnityEngine.Object[] objs = assetBundle.LoadAll();
在本例中assetBundle.mainAsset是GameObject,但是并不代表assetBundle.LoadAll();的返回值數(shù)組的第一個數(shù)據(jù)是GameObject即obj[0]等于assetBundle.mainAsset
assetBundle.mainAsset
AssetBundle.Unload(bool unloadAllLoadedObjects)
清空bundle里的所有資源。釋放相關(guān)內(nèi)存。清空后不能再通過該bundle創(chuàng)建物體。
unloadAllLoadedObjects為false:AssetBundle里的數(shù)據(jù)將會被釋放,不影響已經(jīng)scene中已經(jīng)創(chuàng)建的相關(guān)物體。
unloadAllLoadedObjects為true:不僅AssetBundle里的數(shù)據(jù)將會被釋放,從該bundle創(chuàng)建的貼圖材質(zhì)等等asset將會被清空。如果scene中已經(jīng)物體使用這些,連接將丟失。

讀取場景:當(dāng)AssetBundle下載好后,直接Application.LoadLevel("scene");即可
- //******************************************************
- //AssetBundle.CreateFromMemory -> LoadLevel
- //******************************************************
- usingSystem;
- usingSystem.IO;
- usingUnityEngine;
- public classLoadAssetBundle:MonoBehaviour{
- private AssetBundleassetBundle;
- private AssetBundleCreateRequestrequest;
- voidUpdate () {
- }
- voidOnGUI()
- {
- if(GUI.Button(newRect(0,0,100,50),"Load"))
- {
- byte[] bs =File.ReadAllBytes(Application.dataPath+"/myLevel.unity3d");
- request=AssetBundle.CreateFromMemory(bs);
- }
- if(GUI.Button(newRect(0,50,100,50),"Check"))
- {
- if(request.isDone ==true)
- {
- Application.LoadLevel("scene");
- }
- }
- }
- }
總結(jié):制作AssetBundle主要有1BuildPipeline.BuildAssetBundle非場景2BuildPipeline.BuildStreamedSceneAssetBundle場景
使用AssetBundle主要有1AssetBundle.CreateFromFile 只能是Uncompressed格式2AssetBundle.CreateFromMemory 需要處理request3AssetBundle bundle = www.assetBundle;www又分為2種 (1)WWW www = newWWW(address);
(2)WWW www =WWW.LoadFromCacheOrDownload(address,1,crc); 其中網(wǎng)游用的最多的是LoadFromCacheOrDownload,因?yàn)榈谝淮蜗螺d后就存在本地緩存了,之后就直接從本地緩存讀取.crc是用來做數(shù)據(jù)校驗(yàn)的。
其中推薦LoadFromCacheOrDownload。不推薦CreateFromMemory,因?yàn)樾枰粋€解析建AB結(jié)構(gòu)的過程,比較耗時。CreateFromFile也不是很推薦,因?yàn)橹恢С址菈嚎s格式,所以占容量比較多。
預(yù)制體打包成AssetBundle時:預(yù)制體可以搭腳本,并且指定關(guān)系等都可以照常使用。
要求:
(1)但是腳本必須是工程里有的
(2)AssetBundle里預(yù)制體上搭載的腳本必須和工程里的腳本一致。
否則會提示錯誤。
愛華網(wǎng)



