实例如下:
现在unity3d的帮助文档BuildPipeline.BuildAssetBundle中,复制以下C#代码。
// 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);
}
}
}
Build AssetBundle From Selection - Track dependencies,顾名思义,它能通过当前选中的物体创建AssetBundles数据资源,并且该数据资源包含所有的关联物体。比如,子物体和其他组件(components)。
Build AssetBundle From Selection - No dependency tracking,很明显,这种方法同上面是相对应的,它不包含关联物体,而仅仅输出选中物体本身。
在这个例子中,我们在编辑器中创建一个cube,通过菜单GameObject - Create Other - Cube,在层级视图(Hierachy View)中,会创建了一个新的cube物体,把他拖动到项目视图(Project View)中,称为预置物(Prefabs)。在项目视图中,鼠标右键点击cube,选择Build AssetBundle From Selection - Track dependencies,生成数据资源,并把它存储到项目的AssetBundles目录中。
生成完毕的Cube.unity3d文件,可以根据项目的要求,存储到磁盘的任何位置,或者上传到服务器。
这种手动存储的方法,在项目建立之初能快速的帮助项目建立原型,但随着资源文件的壮大,通过手动来输出明显是不可能的。比较有效的方法,就是写一个函数,来自动创建项目中所有的AssetBundles,同时用一个text文本来标示项目中要创建数据资源的列表清单。(更多Unity3D教程资讯分享尽在Web3D纳金网http://www.narkii.com/)