风宇冲 Unity3D教程宝典之AssetBundles:第一讲

原创文章如需转载请注明:转载自风宇冲Unity3D教程学院

AssetBundles第一讲:基本使用

AssetBundles是从unity导出你选择的assets,它使用特有的压缩格式并且应用可以实时去读取它。包括模型贴图音频等任何asset类型,甚至整个场景。压缩大小基本能达到zip的效果。AssetBundles从设计时就定位为可以很简单就下载到应用里。如果你想包括自定义的binary数据,就要用.bytes后缀,Unity将作为TextAssets导入他们。
注意:AssetBundles并不像Unity官方说的那样,各种unity版本兼容。经测试在unity4中创建的ab,在4中正常使用,但在3.5.0里无法正常使用。说明用AB不能向下兼容。
开发阶段:
(1)创建AssetBundles:
不能是 sceneobjects的objects使用BuildPipeline.BuildAssetBundletargetplatform要指定,不能用默认参数,默认模式是webplayer
  1. usingUnityEngine;
  2. usingUnityEditor;
  3. publicclassExportAssetBundles{
  4. [MenuItem("Assets/BuildAssetBundle From Selection - Track dependencies")]
  5. staticvoidExportResource() {
  6. // Bring up save panel
  7. stringpath=EditorUtility.SaveFilePanel ("SaveResource","","NewResource","unity3d");
  8. if(path.Length!=0) {
  9. // Build the resource file fromthe active selection.
  10. Object[] selection=Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
  11. BuildPipeline.BuildAssetBundle(Selection.activeObject,selection,
  12. path,BuildAssetBundleOptions.CollectDependencies|BuildAssetBundleOptions.CompleteAssets
  13. ,BuildTarget.StandaloneWindows);
  14. Selection.objects =selection;
  15. }
  16. }
  17. [MenuItem("Assets/BuildAssetBundle From Selection - No dependency tracking")]
  18. staticvoidExportResourceNoTrack() {
  19. // Bring up save panel
  20. stringpath=EditorUtility.SaveFilePanel ("SaveResource","","NewResource","unity3d");
  21. if(path.Length!=0) {
  22. // Build the resource file fromthe active selection.
  23. BuildPipeline.BuildAssetBundle(Selection.activeObject,Selection.objects,path);
  24. }
  25. }
  26. }
boolBuildPipeline.BuildAssetBundleExplicitAssetNames(Object[]assets, string[] assetName, string pathName,BuildAssetBundleOptions assetBundleOptions, BuildtargettargetPlatform)
创建bundle并自定义名称。assetName的长度及排列与assets对应。并不是真正改变物体的名称,只是在assetBundle.Load的时候有个唯一对应的名称

对上面代码仅需修改第11行。将BuildPipeline.BuildAssetBundle(Selection.activeObject,selection,

path,BuildAssetBundleOptions.CollectDependencies|BuildAssetBundleOptions.CompleteAssets

,BuildTarget.StandaloneWindows);里的第一个参数mainAsset去掉,并在selection也就是Object[]之后加string[]assetName即可


  1. [MenuItem("Assets/BuildAssetBundle From Selection Names- Trackdependencies")]
  2. staticvoidExportResourceWithNames() {
  3. // Bring up savepanel
  4. stringpath=EditorUtility.SaveFilePanel("SaveResource","","NewResource","unity3d");
  5. if(path.Length!=0) {
  6. // Build the resourcefile from the active selection.
  7. Object[] selection=Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
  8. string[] names=newstring[selection.Length];
  9. for(inti=0;i
  10. {
  11. names[i] =i+"_"+selection[i].name;
  12. }
  13. BuildPipeline.BuildAssetBundleExplicitAssetNames(selection,names,
  14. path,BuildAssetBundleOptions.CollectDependencies|BuildAssetBundleOptions.CompleteAssets
  15. ,BuildTarget.StandaloneWindows);
  16. Selection.objects= selection;
  17. }
  18. }




  1. usingSystem;
  2. usingSystem.IO;
  3. usingUnityEngine;

  4. publicclassLoadAssetBundle:MonoBehaviour{
  5. privateAssetBundleassetBundle;
  6. privateAssetBundleCreateRequestrequest;

  7. voidUpdate () {
  8. }
  9. voidOnGUI()
  10. {
  11. if(GUI.Button(newRect(0,0,100,50),"Load"))
  12. {
  13. byte[] bs =File.ReadAllBytes(Application.dataPath+"/withNames.unity3d");
  14. request=AssetBundle.CreateFromMemory(bs);
  15. }
  16. if(GUI.Button(newRect(0,50,100,50),"Check"))
  17. {
  18. if(request.isDone==true)
  19. {
  20. assetBundle = request.assetBundle;
  21. UnityEngine.Objectobj =assetBundle.Load("0_Cube");
  22. Instantiate(obj);
  23. }
  24. }
  25. }
将场景做成AB时,BuildPipeline.BuildStreamedSceneAssetBundle将一个或者多个场景打包到assetbundle里,可以为任何平台,并总创建单一的压缩.unity3d文件。在下载后,可以用WWW.LoadFromCacheOrDownload从缓存里读取。
  1. usingUnityEngine;
  2. usingUnityEditor;

  3. public classBuildScene:MonoBehaviour{
  4. [MenuItem("Build/BuildWebplayerStreamed")]
  5. staticvoidBuildScenes()
  6. {
  7. string[] levels=newstring[1];
  8. levels[0] ="Assets/scene.unity";
  9. BuildPipeline.BuildStreamedSceneAssetBundle(levels,"Assets/myLevel.unity3d",BuildTarget.StandaloneOSXIntel);
  10. }
  11. }


兼容性
Platform compatibility forAssetBundles
StandaloneWebplayeriOSAndroid
EditorYYYY
StandaloneYY
WebplayerYY
iOSY
AndroidY

(2)上传AssetBundles: 基于你所使用的服务器决定如何上传。

使用阶段:
(1)下载AssetBundles:
1AssetBundle.CreateFromFile:(1)只能用于pc和macstandalone(2)只支持Uncompressed:也就是在build的时候buildoption还要加上UncompressedAssetBundle。(3)必须得是绝对路径。 AssetBundleassetBundle =AssetBundle.CreateFromFile("D:/myBundle4.unity3d");

2AssetBundle.CreateFromMemory(bs);

  1. using System;
  2. using System.IO;
  3. using UnityEngine;
  4. public class LoadAssetBundle : MonoBehaviour {
  5. privateAssetBundle assetBundle;
  6. privateAssetBundleCreateRequest request;
  7. voidUpdate () {
  8. if(request!=null)
  9. print(request.progress);
  10. }
  11. voidOnGUI()
  12. {
  13. if(GUI.Button(new Rect(0,0,100,50),"Load"))
  14. {
  15. byte[] bs =File.ReadAllBytes("D:/myBundle.unity3d");
  16. request =AssetBundle.CreateFromMemory(bs);
  17. }
  18. if(GUI.Button(new Rect(0,50,100,50),"Check"))
  19. {
  20. if(request.isDone == true)
  21. {
  22. print("name:"+request.assetBundle.mainAsset.name);
  23. Instantiate(request.assetBundle.mainAsset);
  24. }
  25. }
  26. }
  27. }

3 AssetBundle bundle = www.assetBundle;注:WWW也是可以读取本地文件的,只需要在路径前file://即可,如WWW myWWW = new WWW("file://E://LSY/wamp/www/cat.jpg");
  1. using System;
  2. using System.IO;
  3. using UnityEngine;
  4. using System.Collections;
  5. public class LoadAssetBundle : MonoBehaviour {
  6. privateAssetBundle assetBundle;
  7. privatestring address ="http://127.0.0.1/AssetBundles/myBundle.unity3d";
  8. voidOnGUI()
  9. {
  10. if(GUI.Button(new Rect(0,0,100,50),"Load web"))
  11. {
  12. StartCoroutine(Load());
  13. }
  14. }
  15. IEnumerator Load() {
  16. // Download the file from theURL. It will not be saved in the Cache
  17. stringAssetName="";
  18. WWW www = newWWW(address);
  19. yield return www;
  20. if (www.error != null)
  21. throw new Exception("WWWdownload had an error:" + www.error);
  22. AssetBundle bundle =www.assetBundle;
  23. if (AssetName == "")
  24. Instantiate(bundle.mainAsset);
  25. else
  26. Instantiate(bundle.Load(AssetName));
  27. // Unload the AssetBundles compressed contents to conservememory
  28. bundle.Unload(false);
  29. }
  30. }
WWW.LoadFromCacheOrDownload
下载过程中可以更换下载地址,并保证版本一致, Webplayer的cache限制在50MB以内。
与普通的www下载仅仅是一句代码的区别
WWW www = new WWW(address);
WWW www =WWW.LoadFromCacheOrDownload(address,1);
  1. using System;
  2. using System.IO;
  3. using UnityEngine;
  4. using System.Collections;
  5. public class LoadAssetBundle : MonoBehaviour {
  6. privateAssetBundle assetBundle;
  7. privatestring address ="http://127.0.0.1/AssetBundles/myBundle.unity3d";
  8. voidOnGUI()
  9. {
  10. if(GUI.Button(new Rect(0,0,100,50),"Load web"))
  11. {
  12. StartCoroutine(Load());
  13. }
  14. }
  15. IEnumerator Load() {
  16. stringAssetName="";
  17. WWW www =WWW.LoadFromCacheOrDownload(address,1);
  18. yield return www;
  19. if (www.error != null)
  20. throw new Exception("WWWdownload had an error:" + www.error);
  21. AssetBundle bundle =www.assetBundle;
  22. if (AssetName == "")
  23. Instantiate(bundle.mainAsset);
  24. else
  25. Instantiate(bundle.Load(AssetName));
  26. // Unload the AssetBundles compressed contents to conservememory
  27. bundle.Unload(false);
  28. }
  29. }

(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();的返回值数组的第一个数据是GameObject即obj[0]等于assetBundle.mainAsset


assetBundle.mainAsset

AssetBundle.Unload(bool unloadAllLoadedObjects)
清空bundle里的所有资源。释放相关内存。清空后不能再通过该bundle创建物体。
unloadAllLoadedObjects为false:AssetBundle里的数据将会被释放,不影响已经scene中已经创建的相关物体。
unloadAllLoadedObjects为true:不仅AssetBundle里的数据将会被释放,从该bundle创建的贴图材质等等asset将会被清空。如果scene中已经物体使用这些,连接将丢失。

【风宇冲】Unity3D教程宝典之AssetBundles:第一讲






读取场景:当AssetBundle下载好后,直接Application.LoadLevel("scene");即可
  1. //******************************************************
  2. //AssetBundle.CreateFromMemory -> LoadLevel
  3. //******************************************************
  4. usingSystem;
  5. usingSystem.IO;
  6. usingUnityEngine;

  7. public classLoadAssetBundle:MonoBehaviour{
  8. private AssetBundleassetBundle;
  9. private AssetBundleCreateRequestrequest;

  10. voidUpdate () {
  11. }
  12. voidOnGUI()
  13. {
  14. if(GUI.Button(newRect(0,0,100,50),"Load"))
  15. {
  16. byte[] bs =File.ReadAllBytes(Application.dataPath+"/myLevel.unity3d");
  17. request=AssetBundle.CreateFromMemory(bs);
  18. }
  19. if(GUI.Button(newRect(0,50,100,50),"Check"))
  20. {
  21. if(request.isDone ==true)
  22. {
  23. Application.LoadLevel("scene");
  24. }
  25. }
  26. }
  27. }

总结:制作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); 其中网游用的最多的是LoadFromCacheOrDownload,因为第一次下载后就存在本地缓存了,之后就直接从本地缓存读取.crc是用来做数据校验的。

其中推荐LoadFromCacheOrDownload。不推荐CreateFromMemory,因为需要一个解析建AB结构的过程,比较耗时。CreateFromFile也不是很推荐,因为只支持非压缩格式,所以占容量比较多。

预制体打包成AssetBundle时:预制体可以搭脚本,并且指定关系等都可以照常使用。

要求:

(1)但是脚本必须是工程里有的

(2)AssetBundle里预制体上搭载的脚本必须和工程里的脚本一致。

否则会提示错误。

  

爱华网本文地址 » http://www.413yy.cn/a/25101015/277933.html

更多阅读

杜星宇:论薛宝钗之结局

红学界关于宝钗之结局,主要有“守寡说”,“早夭说”和“嫁贾雨村说”三种不同观点。这三种观点粗略看去似乎都有道理,但仔细推敲后便不难发现“守寡说”与“嫁贾雨村说”均存在着漏洞。持“守寡说”者较多,恕不能一一举例说明。他们的

6950玩机宝典 京瓷6950dn打印机驱动

6950改卡机玩机宝典之一一、PPC基础知识1.关于6950的中文说明书Xv6950不是大中华区的机子,不可能有中文说明书,我们可以查考中国电信发布的S900c的中文说明书,来了解6950的操作和硬件资料,大家可以通过以下连接下载来做参考:连接2.以下

原创连载 80后怀旧宝典之电视剧·少儿电视剧 80后怀旧游戏

《小龙人》《少年特工》《十六岁的花季》《第三军团》对于80后来说,现在的时代,早已不是电视剧的时代,我们呆在电脑前面的时间,要远远多过在电视机前的时间。而每晚都要守在电视机前等着看两集电视剧的记忆,属于我们还是小屁孩的年纪。所

QQ骂人宝典之骂人歇后语大全 qq骂人宝典下载

一二三四五六七--- 忘(王)八一个耳朵大,一个耳朵小---猪狗养的一把粉打在后颈窝---釉子上反了二十一天不出鸡---坏蛋三伏天卖不掉的肉---臭货三角坟地---缺德三年不洗口--- 一张臭嘴三年不屙屎---粪胀(混帐)大姑娘养的---丑东西大车

声明:《风宇冲 Unity3D教程宝典之AssetBundles:第一讲》为网友白满川分享!如侵犯到您的合法权益请联系我们删除