有三种类函数可用于构建资源包 (AssetBundles):
我们使用编辑器脚本构建资源包。BuildPipeline.BuildAssetBundle 脚本文档中有相关基本示例。
根据此示例,将上述链接中的脚本复制并粘贴至新 C# 脚本,并以 ExportAssetBundles 命名。此脚本应位于名为编辑器 (Editor) 的文件夹中,以便其可在Unity 编辑器中运行。
现在在
菜单中,应可看见两个新菜单选项。在此示例中,您应新建预设。首先,可通过转至
在层级视图 (Hierarchy View) 中新建立方体 (Cube)。然后将立方体 (Cube) 从层级视图 (Hierarchy View) 拖放至工程视图 (Project View),这将创建该对象的预设。然后,应在工程窗口右击立方体 (Cube) 预设并依次选择 Cube.unity3d,现在,工程窗口将以下图形式显示。
。 此时将显示一个窗口提示您保存打包的资源。如果新建一个名为“资源包 (AssetBundles)”的文件夹并将立方体另存为此时,可将资源包 (AssetBundle) Cube.unity3d 移至本地存储的其他位置,或将其上传至所选服务器。
可在调用 BuildPipeline.BuildAssetBundle 前使用 AssetDatabase.ImportAsset 强制重新导入资源,然后使用 AssetPostprocessor.OnPreprocessTexture 设置所需属性。以下示例将介绍构建资源包 (Asset Bundle) 时如何设置不同的纹理压缩率。
// Builds an asset bundle from the selected objects in the project view, // and changes the texture format using an AssetPostprocessor. using UnityEngine; using UnityEditor; public class ExportAssetBundles { // Store current texture format for the TextureProcessor. public static TextureImporterFormat textureFormat; [MenuItem("Assets/Build AssetBundle From Selection - PVRTC_RGB2")] static void ExportResourceRGB2 () { textureFormat = TextureImporterFormat.PVRTC_RGB2; ExportResource(); } [MenuItem("Assets/Build AssetBundle From Selection - PVRTC_RGB4")] static void ExportResourceRGB4 () { textureFormat = TextureImporterFormat.PVRTC_RGB4; ExportResource(); } 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); foreach (object asset in selection) { string assetPath = AssetDatabase.GetAssetPath((UnityEngine.Object) asset); if (asset is Texture2D) { // Force reimport thru TextureProcessor. AssetDatabase.ImportAsset(assetPath); } } BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets); Selection.objects = selection; } } }
// Changes the texture format when building the Asset Bundle. using UnityEngine; using UnityEditor; public class TextureProcessor :AssetPostprocessor { void OnPreprocessTexture() { TextureImporter importer = assetImporter as TextureImporter; importer.textureFormat = ExportAssetBundles.textureFormat; } }
还可使用 AssetDatabase.ImportAssetOptions 控制资源导入方式。
从上述示例可看出,首次使用资源包 (AssetBundles) 时,完全可手动构建资源包。但随着工程逐渐增大和资源数量逐渐增加,手动完成此流程则费时费力。一个更好的办法是编写函数构建一个工程的所有资源包 (AssetBundles)。例如,可使用文本文件将资源 (Asset) 文件映射到资源包 (AssetBundle) 文件。
Page last updated: 2013-06-26