0
点赞
收藏
分享

微信扫一扫

unity3D制作并使用Assetbundles方法


在网页中为了控制.unity文件的大小,加速载入速度,可以把系统用到的资源制作成Assestbundles,根据需要进行动态的加载和卸载。具体作法:



1、使用脚本重新定义系统菜单,添加一个制作Assetbunles的菜单命令:


// C# Example 
 
 
 

   // Builds an asset bundle from the selected objects in the project view. 
 
 
 

   // Once compiled go to "Menu" -> "Assets" and select one of the choices 
 
 
 

   // to build the Asset Bundle 
 
 
 

     
 
 
 

   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); 
 
 
 

   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); 
 
 
 

   } 
 
 
 

   } 
 
 
 

   }


以上脚本按类命名后放置在工程文件夹内Assets目录内的Edit文件夹内(如没有,自行新建)。这时如脚本描述的在菜单栏内的Assets下会出现Build AssetBundle From Selection的两个菜单,选中需要制作Assetbunles的资源生成即可。



2、使用www按需载入Assetbundle,举例如下


function Start () { 
  
 
  

     var url = "file:///D:/temp/XXX.unity3d"; 
   
 
   
url)); 
   
 
  

    } 
  
 
 

    function LoadAsset (url : String) { 
  
 
  

    var www : WWW = new WWW (url); 
  
 
  

    yield www; 
  
 
  

    var present : GameObject; 
  
 
  

    present = GameObject.Find("present"); 
  
 
  

    if( present != null ) 
  
 
  

    Destroy(present); 
  
 
  

    present = Instantiate(www.assetBundle.mainAsset); 
  
 
  

    present.name = "present"; //暂时把名字叫做“present” 
  
 
  

    }

举报

相关推荐

0 条评论