在Unity開發中有許許多多的UI界面,包含着不同的元件,比如Button、Image等,我們需要按正确的路徑找到它們并持有它們,這個步驟在界面十分龐大的時候,會十分繁瑣易錯。本文介紹的自動生成代碼工具就是為了解決這一困境,可以自動擷取那些我們想要的元件,一鍵生成,希望對你有所幫助。
生成代碼展示
設計思路
我們要使得對象自動生成代碼,無非就是分三步,第一步找到這個對象,第二步記錄這個對象身上所有需要生成代碼的元件,第三步建立一份檔案寫入我們記錄好的内容。
操作流程
- 制作好我們需要的預制體界面,要擷取元件的對象用T_來開頭
- 右鍵界面根節點,點選SpawnUICode(生成UI模闆),會彈出操作視窗
- 點選視窗的選擇腳本要生成的子產品,會彈出我們預設的子產品下拉菜單,選擇我們對應的子產品,即可将腳本生成在選中的子產品下。
源碼
彈出視窗代碼
class GeneratePathSelectWindow : EditorWindow
{
private string[] path = new string[]
{
"Common",
"Store",
"Role",
"Host",
};
private static GameObject selectGo;
public void ShowWindow(GameObject go)
{
selectGo = go;
EditorWindow.GetWindow(typeof(GeneratePathSelectWindow));
}
void OnGUI()
{
if (GUILayout.Button("選擇腳本要生成的子產品"))
{
ShowGenericMenu();
}
}
private void ShowGenericMenu()
{
GenericMenu menu = new GenericMenu(); //初始化GenericMenu
for (int i = 0; i < path.Length; i++)
{
menu.AddItem(new GUIContent(path[i]), false, SelectPath, path[i]); //向菜單中添加菜單項
}
menu.ShowAsContext(); //顯示菜單
}
void SelectPath(object floderName)
{
string t = floderName.ToString();
Debug.Log("選擇路徑:" + floderName);
UICodeSpawner.SpawnUICode(selectGo, t);//生成腳本代碼
}
}
内容寫入代碼
private static void SpawnPanelCode(GameObject gameObject)
{
Path2WidgetCachedDict?.Clear();
Path2WidgetCachedDict = new Dictionary<string, List<Component>>();
FindAllWidgets(gameObject.transform, "");
SpawnCodeForPanel(gameObject);
AssetDatabase.Refresh();
}
private static void SpawnCodeForPanel(GameObject gameObject)
{
var strPanelName = gameObject.name;
var strFilePath = Application.dataPath + defaultUIPath + selectFolderName + "/UIBehaviour/" + strPanelName;
if (!Directory.Exists(strFilePath))
{
Debug.LogError("請先(SpawnerUICode)生成UI代碼模闆");
Directory.CreateDirectory(strFilePath);
return;
}
SpawnCodeForPanelComponentBehaviour(gameObject);
}
private static void SpawnCodeForPanelComponentBehaviour(GameObject gameObject)
{
if (null == gameObject)
{
return;
}
string strDlgName = gameObject.name;
string strDlgComponentName = gameObject.name + "View";
string strFilePath = Application.dataPath + defaultUIPath + selectFolderName + "/UIBehaviour/" + strDlgName;
if (!Directory.Exists(strFilePath))
{
Directory.CreateDirectory(strFilePath);
}
strFilePath = Application.dataPath + defaultUIPath + selectFolderName + "/UIBehaviour/" + strDlgName +
"/" + strDlgComponentName + ".cs";
StreamWriter sw = new StreamWriter(strFilePath, false, Encoding.UTF8);
StringBuilder strBuilder = new StringBuilder();
strBuilder.AppendLine("using UnityEngine;");
strBuilder.AppendLine("using UnityEngine.UI;");
strBuilder.AppendLine();
strBuilder.AppendLine("namespace AutoBuildCode");
strBuilder.AppendLine("{");
strBuilder.AppendLine("\t/// <summary>");
strBuilder.AppendLine("\t/// 此檔案為腳本自動生成并且覆寫;");
strBuilder.AppendLine("\t/// 非必要請不要在此作修改");
strBuilder.AppendLine("\t/// </summary>");
strBuilder.AppendFormat("\tpublic class {0} : MonoBehaviour \r\n", strDlgComponentName)
.AppendLine("\t{");
strBuilder.AppendFormat("\t\tprivate Transform uiTransform = null;\r\n");
CreateDeclareCode(ref strBuilder);
strBuilder.AppendLine();
CreateWidgetBindCode(ref strBuilder, gameObject.transform);
CreateDestroyWidgetCode(ref strBuilder);
strBuilder.AppendLine("\t}");
strBuilder.AppendLine("}");
sw.Write(strBuilder);
sw.Flush();
sw.Close();
}
private static void CreateDestroyWidgetCode(ref StringBuilder strBuilder)
{
strBuilder.AppendFormat("\t\tpublic void DestroyWidget()");
strBuilder.AppendLine("\n\t\t{");
CreateDlgWidgetDisposeCode(ref strBuilder);
strBuilder.AppendFormat("\t\t\tthis.uiTransform = null;\r\n");
strBuilder.AppendLine("\t\t}\n");
}
private static void CreateDlgWidgetDisposeCode(ref StringBuilder strBuilder, bool isSelf = false)
{
string pointStr = isSelf ? "self" : "this";
foreach (KeyValuePair<string,List<Component>> pair in Path2WidgetCachedDict)
{
foreach (var info in pair.Value)
{
Component widget = info;
string strClassType = widget.GetType().ToString();
string widgetName = widget.name + strClassType.Split('.').ToList().Last();
strBuilder.AppendFormat("\t\t {0}.m_{1} = null;\r\n", pointStr, widgetName);
}
}
}
private static void CreateWidgetBindCode(ref StringBuilder strBuilder, Transform transRoot)
{
foreach (KeyValuePair<string, List<Component>> pair in Path2WidgetCachedDict)
{
foreach (var info in pair.Value)
{
Component widget = info;
string strPath = GetWidgetPath(widget.transform, transRoot);
string strClassType = widget.GetType().ToString();
string strInterfaceType = strClassType;
string widgetName = widget.name + strClassType.Split('.').ToList().Last();
strBuilder.AppendFormat(" public {0} {1}\r\n", strInterfaceType, widgetName);
strBuilder.AppendLine(" {");
strBuilder.AppendLine(" get");
strBuilder.AppendLine(" {");
strBuilder.AppendFormat(" if( this.m_{0} == null )\n", widgetName);
strBuilder.AppendLine(" {");
strBuilder.AppendFormat(
" this.m_{0} = transform.Find(\"{1}\").GetComponent<{2}>();\r\n",
widgetName, strPath, strInterfaceType);
strBuilder.AppendLine(" }");
strBuilder.AppendFormat(" return this.m_{0};\n", widgetName);
strBuilder.AppendLine(" }");
strBuilder.AppendLine(" }\n");
}
}
}
static string GetWidgetPath(Transform obj, Transform root)
{
string path = obj.name;
while (obj.parent != null && obj.parent != root)
{
obj = obj.transform.parent;
path = obj.name + "/" + path;
}
return path;
}
private static void CreateDeclareCode(ref StringBuilder strBuilder)
{
foreach (KeyValuePair<string, List<Component>> pair in Path2WidgetCachedDict)
{
foreach (var info in pair.Value)
{
Component widget = info;
string strClassType = widget.GetType().ToString();
string widgetName = widget.name + strClassType.Split('.').ToList().Last();
strBuilder.AppendFormat("\t\tprivate {0} m_{1}=null;\r\n", strClassType, widgetName);
}
}
}
/// <summary>
/// 把所有的元件配置都裝好了,裝在了Path2WidgetCachedDict
/// </summary>
/// <param name="trans"></param>
/// <param name="strPath"></param>
private static void FindAllWidgets(Transform trans, string strPath)
{
if (null == trans)
{
return;
}
for (int nIndex = 0; nIndex < trans.childCount; ++nIndex) //隻算兒子,不算孫子
{
Transform child = trans.GetChild(nIndex);
string strTemp = strPath + "/" + child.name;
bool isSubUI = child.name.StartsWith(CommonUIPrefix);
if (child.name.StartsWith(UIWidgetPrefix))
{
foreach (var uiComponent in WidgetInterfaceList)
{
Component component = child.GetComponent(uiComponent);
if (null == component)
{
continue;
}
if (Path2WidgetCachedDict.ContainsKey(child.name))
{
Path2WidgetCachedDict[child.name].Add(component);
continue;
}
List<Component> componentsList = new List<Component>();
componentsList.Add(component);
Path2WidgetCachedDict.Add(child.name, componentsList);
}
}
if (isSubUI)
{
Debug.Log($"遇到子UI,{child.name},不生成子UI項代碼");
continue;
}
FindAllWidgets(child, strTemp);
}
}
static UICodeSpawner()
{
WidgetInterfaceList = new List<string>();
WidgetInterfaceList.Add("Button");
WidgetInterfaceList.Add("Text");
WidgetInterfaceList.Add("TMP_Text");
WidgetInterfaceList.Add("InputField");
WidgetInterfaceList.Add("TMP_InputField");
WidgetInterfaceList.Add("Dropdown");
WidgetInterfaceList.Add("TMP_Dropdown");
WidgetInterfaceList.Add("Input");
WidgetInterfaceList.Add("Scrollbar");
WidgetInterfaceList.Add("ToggleGroup");
WidgetInterfaceList.Add("Toggle");
WidgetInterfaceList.Add("Slider");
WidgetInterfaceList.Add("ScrollRect");
WidgetInterfaceList.Add("Image");
WidgetInterfaceList.Add("RawImage");
WidgetInterfaceList.Add("Canvas");
WidgetInterfaceList.Add("CanvasGroup");
}
工程項目
連結:https://pan.baidu.com/s/1yToMdgKa1AxsbfWrqu8YMA
提取碼:vabd