自:http://blog.sina.com.cn/s/blog_471132920101gz8z.html
原創(chuàng)文章如需轉(zhuǎn)載請(qǐng)注明:轉(zhuǎn)載自風(fēng)宇沖Unity3D教程學(xué)院
???????
AssetBundles第一講:基本使用AssetBundles是從unity導(dǎo)出你選擇的assets,它使用特有的壓縮格式并且應(yīng)用可以實(shí)時(shí)去讀取它。包括模型貼圖音頻等任何asset類型,甚至整個(gè)場(chǎng)景。壓縮大小基本能達(dá)到zip的效果。AssetBundles從設(shè)計(jì)時(shí)就定位為可以很簡(jiǎn)單就下載到應(yīng)用里。如果你想包括自定義的binary數(shù)據(jù),就要用.bytes后綴,Unity將作為TextAssets導(dǎo)入他們。 注意: AssetBundles并不像Unity官方說的那樣,各種unity版本兼容。經(jīng)測(cè)試在unity4中創(chuàng)建的ab,在4中正常使用,但在3.5.0里無法正常使用。說明用AB不能向下兼容。
開發(fā)階段:(1)創(chuàng)建AssetBundles:
不能是scene objects的objects使用
BuildPipeline.BuildAssetBundle? targetplatform要指定,不能用默認(rèn)參數(shù),默認(rèn)模式是webplayer
?
using?UnityEngine;using?UnityEditor;public?class?ExportAssetBundles {????[MenuItem("Assets/Build AssetBundle From Selection - Track dependencies")]????static?void?ExportResource () {????????// Bring up save panel????????string?path =?EditorUtility.SaveFilePanel ("Save Resource",?"",?"New Resource","unity3d");????????if?(path.Length !=?0) {????????????// Build the resource file from the 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/Build AssetBundle From Selection - No dependency tracking")]????static?void?ExportResourceNoTrack () {????????// Bring up save panel????????string?path =?EditorUtility.SaveFilePanel ("Save Resource",?"",?"New Resource","unity3d");????????if?(path.Length !=?0) {????????????// Build the resource file from the active selection.????????????BuildPipeline.BuildAssetBundle(Selection.activeObject,?Selection.objects, path);????????}????}}bool BuildPipeline.BuildAssetBundleExplicitAssetNames(Object[] assets, string[] assetName, string pathName, BuildAssetBundleOptions assetBundleOptions, Buildtarget targetPlatform)
創(chuàng)建bundle并自定義名稱。assetName的長(zhǎng)度及排列與assets對(duì)應(yīng)。并不是真正改變物體的名稱,只是在assetBundle.Load的時(shí)候有個(gè)唯一對(duì)應(yīng)的名稱
對(duì)上面代碼僅需修改第11行。將BuildPipeline.BuildAssetBundle(Selection.activeObject, selection,?
path,?BuildAssetBundleOptions.CollectDependencies |?BuildAssetBundleOptions.CompleteAssets
,BuildTarget.StandaloneWindows); 里的第一個(gè)參數(shù)mainAsset去掉,并在selection也就是Object[]之后加string[] assetName即可
?
[MenuItem("Assets/Build AssetBundle From Selection Names- Track dependencies")]????static?void?ExportResourceWithNames () {????????// Bring up save panel????????string?path =?EditorUtility.SaveFilePanel ("Save Resource",?"",?"New Resource","unity3d");????????if?(path.Length !=?0) {????????????// Build the resource file from the active selection.????????????Object[] selection =?Selection.GetFiltered(typeof(Object),?SelectionMode.DeepAssets);string[] names =?new?string[selection.Length];for(int?i =0;i{names[i] =?i+"_"+ selection[i].name;}????????????BuildPipeline.BuildAssetBundleExplicitAssetNames( selection,names,?path,?BuildAssetBundleOptions.CollectDependencies |BuildAssetBundleOptions.CompleteAssets,BuildTarget.StandaloneWindows);????????????Selection.objects = selection;????????}????}?
?
?
using?System;using?System.IO;using?UnityEngine; public?class?LoadAssetBundle :?MonoBehaviour?{private?AssetBundle?assetBundle;private?AssetBundleCreateRequest?request; void?Update () {}void?OnGUI(){if(GUI.Button(new?Rect(0,0,100,50),"Load")){byte[] bs = File.ReadAllBytes(Application.dataPath+?"/withNames.unity3d");request =?AssetBundle.CreateFromMemory(bs);}if(GUI.Button(new?Rect(0,50,100,50),"Check")){if(request.isDone ==?true){assetBundle = request.assetBundle;UnityEngine.Object?obj = assetBundle.Load("0_Cube");Instantiate(obj);}}}?
?
將場(chǎng)景做成AB時(shí),
BuildPipeline.BuildStreamedSceneAssetBundle 將一個(gè)或者多個(gè)場(chǎng)景打包到asset bundle里,可以為任何平臺(tái),并總創(chuàng)建單一的壓縮.unity3d文件。 在下載后,可以用WWW.LoadFromCacheOrDownload從緩存里讀取。?
using?UnityEngine;using?UnityEditor; public class?BuildScene :?MonoBehaviour?{[MenuItem?("Build/BuildWebplayerStreamed")]static?void?BuildScenes(){string?[] levels =?new?string[1];levels[0] =?"Assets/scene.unity";BuildPipeline.BuildStreamedSceneAssetBundle(levels,?"Assets/myLevel.unity3d",BuildTarget.StandaloneOSXIntel);}}兼容性
| Platform compatibility for AssetBundles |
| ? | Standalone | Webplayer | iOS | Android |
| Editor | Y | Y | Y | Y |
| Standalone | Y | Y | ? | ? |
| Webplayer | Y | Y | ? | ? |
| iOS | ? | ? | Y | ? |
| Android | ? | ? | ? | Y |
(2)上傳AssetBundles: 基于你所使用的服務(wù)器決定如何上傳。
使用階段:(1)下載AssetBundles:
1 AssetBundle.CreateFromFile:? (1)只能用于pc和mac standalone (2)只支持Uncompressed:也就是在build的時(shí)候buildoption還要加上UncompressedAssetBundle?。 (3)必須得是絕對(duì)路徑。 AssetBundle assetBundle = AssetBundle.CreateFromFile("D:/myBundle4.unity3d");
2 AssetBundle.CreateFromMemory(bs); using System;using System.IO;using UnityEngine;public class LoadAssetBundle : MonoBehaviour {????private AssetBundle assetBundle;????private AssetBundleCreateRequest?request;????void Update () {????????if(request!=null)????????????print(request.progress);????}???????void OnGUI()????{????????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 {????private AssetBundle assetBundle;????private string address = "http://127.0.0.1/AssetBundles/myBundle.unity3d";???????void OnGUI()????{????????if(GUI.Button(new Rect(0,0,100,50),"Load web"))????????{????????????StartCoroutine(Load());????????}????}???????IEnumerator Load() {???????// Download the file from the URL. It will not be saved in the Cache???????string????AssetName="";???????WWW www = new WWW(address);???????yield return www;???????if (www.error != null)???????????throw new Exception("WWW download 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 conserve memory???????????????bundle.Unload(false);???}}WWW.LoadFromCacheOrDownload
下載過程中可以更換下載地址,并保證版本一致, 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 {????private AssetBundle assetBundle;????private string address = "http://127.0.0.1/AssetBundles/myBundle.unity3d";???????void OnGUI()????{????????if(GUI.Button(new Rect(0,0,100,50),"Load web"))????????{????????????StartCoroutine(Load());????????}????}???????IEnumerator Load() {???????string????AssetName="";???????WWW www = WWW.LoadFromCacheOrDownload(address,1);???????yield return www;???????if (www.error != null)???????????throw new Exception("WWW download 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 conserve memory???????????????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ù)組的第一個(gè)數(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ù)將會(huì)被釋放,不影響已經(jīng)scene中已經(jīng)創(chuàng)建的相關(guān)物體。
unloadAllLoadedObjects為true: 不僅AssetBundle里的數(shù)據(jù)將會(huì)被釋放,從該bundle創(chuàng)建的貼圖材質(zhì)等等asset將會(huì)被清空。如果scene中已經(jīng)物體使用這些,連接將丟失。
讀取場(chǎng)景: 當(dāng)AssetBundle下載好后,直接Application.LoadLevel("scene");即可
?
//******************************************************//AssetBundle.CreateFromMemory -> LoadLevel//******************************************************using?System;using?System.IO;using?UnityEngine; public class?LoadAssetBundle :?MonoBehaviour?{private AssetBundle?assetBundle;private AssetBundleCreateRequest?request; void?Update () {}void?OnGUI(){if(GUI.Button(new?Rect(0,0,100,50),"Load")){byte[] bs = File.ReadAllBytes(Application.dataPath+?"/myLevel.unity3d");request =?AssetBundle.CreateFromMemory(bs);}if(GUI.Button(new?Rect(0,50,100,50),"Check")){if(request.isDone ==?true){Application.LoadLevel("scene");}}}} 總結(jié): 制作AssetBundle主要有 1?BuildPipeline.BuildAssetBundle?非場(chǎng)景 2?BuildPipeline.BuildStreamedSceneAssetBundle ?場(chǎng)景 使用AssetBundle主要有 1 AssetBundle.CreateFromFile ??只能是Uncompressed格式 2 AssetBundle.CreateFromMemory ???需要處理request 3 AssetBundle bundle = www.assetBundle; ?www又分為2種 (1)WWW www = new WWW(address);
??(2)WWW www = WWW.LoadFromCacheOrDownload(address,1,crc); 其中網(wǎng)游用的最多的是LoadFromCacheOrDownload,因?yàn)榈谝淮蜗螺d后就存在本地緩存了,之后就直接從本地緩存讀取.crc是用來做數(shù)據(jù)校驗(yàn)的。
其中推薦?LoadFromCacheOrDownload。不推薦CreateFromMemory,因?yàn)樾枰粋€(gè)解析建AB結(jié)構(gòu)的過程,比較耗時(shí)。CreateFromFile也不是很推薦,因?yàn)橹恢С址菈嚎s格式,所以占容量比較多。
?
預(yù)制體打包成AssetBundle時(shí):預(yù)制體可以搭腳本,并且指定關(guān)系等都可以照常使用。
要求:
(1)但是腳本必須是工程里有的
(2)AssetBundle里預(yù)制體上搭載的腳本必須和工程里的腳本一致。
否則會(huì)提示錯(cuò)誤。
轉(zhuǎn)載于:https://www.cnblogs.com/wonderKK/p/4266681.html
總結(jié)
以上是生活随笔為你收集整理的(转)【风宇冲】Unity3D教程宝典之AssetBundles:第一讲的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。