代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class BundleEditor
{
#region 路径
public static string ABCONFIGPATH="Asset/Editor/ABConfig.asset";
#endregion
/// <summary>
/// 存放所有的文件夹
/// 所有的文件夹ab包的Dic
/// </summary>
/// <typeparam name="string">key ab包名</typeparam>
/// <typeparam name="string">value 路径</typeparam>
/// <returns></returns>
private static Dictionary<string,string> m_AllFileDir=new Dictionary<string, string>();
/// <summary>
/// 过滤的List
/// 在打AB包时,如果已经存在文件夹里了,那么在打包单个文件夹的时候就不需要再进行打包了
/// </summary>
/// <typeparam name="string"></typeparam>
/// <returns></returns>
private static List<string> m_AllFileABList=new List<string>();
/// <summary>
/// 单个Prefab的ab包
/// </summary>
/// <typeparam name="string">key ab包名</typeparam>
/// <typeparam name="string">value 所有的依赖项</typeparam>
/// <returns></returns>
private static Dictionary<string,List<string>> m_AllPrefabDir=new Dictionary<string, List<string>>();
[MenuItem("Tools/打包")]
public static void Build()
{
m_AllFileDir.Clear();
m_AllFileABList.Clear();
ABConfig abConfig=AssetDatabase.LoadAssetAtPath<ABConfig>(ABCONFIGPATH);
//把配置表中的文件夹里的所有的要打的ab包加到文件夹字典当中
foreach(ABConfig.FileDieABName fileDir in abConfig.m_AllFileDirAB)
{
if(m_AllFileDir.ContainsKey(fileDir.ABName))
{
Debug.LogError("AB包配置名字重复,请检查");
}
else{
m_AllFileDir.Add(fileDir.ABName,fileDir.Path);
m_AllFileABList.Add(fileDir.Path);
}
}
//返回的为GUID 查找到指定路径下的所有Prefab
string[] allStr=AssetDatabase.FindAssets("t:Prefab",abConfig.m_AllPrefabPath.ToArray());
for(int i=0;i<allStr.Length;i++)
{
string path=AssetDatabase.GUIDToAssetPath(allStr[i]);
EditorUtility.DisplayProgressBar("查找Prefab","Prefab:"+path,i*1.0f/allStr.Length);
if(!ContainAllFileAB(path))
{
//根据路径加载出这个prefab
GameObject obj=AssetDatabase.LoadAssetAtPath<GameObject>(path);
//得到这个prefab的所有的依赖项
string[] allDepend=AssetDatabase.GetDependencies(path);
//存储所有的依赖项
List<string> allDependPath=new List<string>();
//遍历所有的依赖
for(int j=0;j<allDepend.Length;j++)
{
//判断当前依赖项是否已经被打包了或者是不是脚本
if (!ContainAllFileAB(allDepend[j])&&!allDepend[j].EndsWith(".cs"))
{
m_AllFileABList.Add(allDepend[j]);
allDependPath.Add(allDepend[j]);
}
}
if (m_AllPrefabDir.ContainsKey(obj.name))
{
Debug.LogError("存在相当名字的Prefab:"+obj.name);
}
else
{
m_AllPrefabDir.Add(obj.name,allDependPath);
}
}
}
EditorUtility.ClearProgressBar();
}
/// <summary>
/// 判断是否已经存在过滤的List中了
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static bool ContainAllFileAB(string path)
{
for(int i=0;i<m_AllFileABList.Count;i++)
{
if(m_AllFileABList[i]==path||path.Contains(m_AllFileABList[i]))
{
return true;
}
}
return false;
}
}
重点:
1.加载Prefab的所有依赖项
string[] allDepend=AssetDatabase.GetDependencies(path);
总结:
1.把自定义配置表中的文件夹里的所有的要打的ab包加到文件夹字典当中
2.查找到指定路径下的所有Prefab
3.查找Prefab的依赖项,判断是否在过滤的集合中,如果在,代表以及被打包到文件夹中
4.把单个Prefab和Prefab的依赖存到一个字典中·,用来进行单独打包