using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
public class BundleBuilder : Editor
{
//资源存放路径
static string assetsDir = Application.dataPath + "/AssetBundleBuilder/Res";
//打包后存放路径
//const string assetBundlesPath = "Assets/AssetBundleBuilder/AssetBundles";
const string assetBundlesPath = "Assets/StreamingAssets/One"; //打包后路径,用哪个都行,自己选,如果选了上边的,需要自己再判断下是否有打包路径
//string streaming = "Assets/StreamingAssets";
[MenuItem("Tool/AutoBundleAll")]
static void AutoBundleAll()
{
//清除所有的AssetBundleName
ClearAssetBundlesName();
//设置指定路径下所有需要打包的assetbundlename
SetAssetBundlesName(assetsDir);
//打包所需要打包的asset
if (!Directory.Exists("Assets/StreamingAssets/One"))
{
Directory.CreateDirectory("Assets/StreamingAssets/One");
BuildPipeline.BuildAssetBundles(assetBundlesPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
else
{
BuildPipeline.BuildAssetBundles(assetBundlesPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
}
[MenuItem("Tool/BuildWithName")]
static void BuildWithName()
{
BuildPipeline.BuildAssetBundles(assetBundlesPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
/// <summary>
/// 清除AssetBundlesName
/// </summary>
private static void ClearAssetBundlesName()
{ //获取
string[] abNames = AssetDatabase.GetAllAssetBundleNames(); //读取所有AssetBundleNames
//清除
for (int i = 0; i < abNames.Length; i++)
{
AssetDatabase.RemoveAssetBundleName(abNames[i], true);//逐个清除BundleName
}
}
/// <summary>
/// 设置在指定路径下的AssetBundlesName
/// </summary>
/// <param name="assetsDir">指定路径</param>
private static void SetAssetBundlesName(string assetPath)
{
//先获取指定路径下的所有Asset,包括子文件夹下的资源
DirectoryInfo dir = new DirectoryInfo(assetPath);
FileSystemInfo[] files = dir.GetFileSystemInfos();//GetFileSystemInfos方法可以获取指定路径下的文件以及子文件夹下的文件
//var arr= dir.GetDirectories();//************** 可以查询子文件夹的名字****************
//foreach (var item in arr)
//{
// Debug.Log(item.Name);
//} //************** 方便以后查询文件夹,带星号注释解开后可以打印Bundle内文件名称
for (int i = 0; i < files.Length; i++)
{
if (files[i] is DirectoryInfo) //如果是文件夹则递归处理
{
SetAssetBundlesName(files[i].FullName); //FullName是全路径
}
else if (!files[i].Name.EndsWith(".meta")) //如果是文件,则设置AssetBundlesName,当然要排除.meta文件
{
SetABName(files[i].FullName); //逐个设置AssetBundleName
}
}
}
/// <summary>
/// 设置单个AssetBundle的Name
/// </summary>
/// <param name="fullName">assetPath</param>
private static void SetABName(string assetPath)
{
//首先确定路径
string importerPath = "Assets" + assetPath.Substring(Application.dataPath.Length); //输入路径必须以Assets资源文件夹为起始路径
AssetImporter assetImporter = AssetImporter.GetAtPath(importerPath); //目的为获取完整路径,Asset
//Debug.Log(assetImporter.ToString());
//Debug.Log(importerPath);
//去除路径多余字符
string tempName = assetPath.Substring(assetPath.LastIndexOf(@"\") + 1);
string assetName = tempName.Remove(tempName.LastIndexOf("."));
assetImporter.assetBundleName = assetName;
}
}