介绍一种在Unity编辑器选中prefab打包成ab的方式:
1.多个资源对象打包成一个ab文件
2.每个资源对象单独生成ab文件
using UnityEngine;
using UnityEditor;
using System.IO;
public class AssetBundleTools : Editor
{
//ab文件输出目录
private static readonly string destPath = Application.streamingAssetsPath;
public static string DestPath
{
get {
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
return destPath;
}
}
/// <summary>
/// 所选资源打包为一个ab文件
/// </summary>
[MenuItem("AssetBundleTools/BuildMix")]
private static void PackageAssetBundleMix()
{
AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
buildMap[0].assetBundleName = "bundlename"; //生成的ab名
Object[] objs = Selection.objects;
string[] assets = new string[objs.Length];
for (int i = 0; i < objs.Length; i++)
{
assets[i] = AssetDatabase.GetAssetPath(objs[i]); //获取文件工程相对路径
}
buildMap[0].assetNames = assets;
if (BuildPipeline.BuildAssetBundles(DestPath, buildMap, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget))
{
Debug.Log(buildMap[0].assetNames + "Package Success");
}
else {
Debug.Log(buildMap[0].assetNames + "Package Faild");
}
AssetDatabase.Refresh();
}
/// <summary>
/// 所选文件分别打包为独立ab文件
/// </summary>
[MenuItem("AssetBundleTools/BuildSingle")]
private static void PackageAssetBundleSingle()
{
Object[] objs = Selection.objects;
AssetBundleBuild[] buildMap = new AssetBundleBuild[objs.Length];
for (int i = 0; i < objs.Length; i++)
{
string[] assets = new string[] { AssetDatabase.GetAssetPath(objs[i]) };
buildMap[i].assetBundleName = objs[i].name;
buildMap[i].assetNames = assets;
}
if (BuildPipeline.BuildAssetBundles(DestPath, buildMap, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget))
Debug.Log("Package Success");
else
Debug.Log("Package Faild");
AssetDatabase.Refresh();
}
}