unity获取UI组件结构的小工具

写这个工具的原因 之前写项目的时候,界面ui多了感觉绑定组件的时候觉得很麻烦,就在想能不能用代码创建一个脚本自动获取组件
思路 将每个对象的声明,初始化,和destroy代码,储存到一个类中。然后将代码替换到模板代码中声明,初始化和destroy相应的位置,然后生成脚本到相应的位置
开始撸代码 声明:private Button xxx_but;
要声明组件我们需要知道组件的类型,因此先设计一个查询组件类型的字典

public static Dictionary typMap = new Dictionary() { {"but",typeof(Button).Name }, {"txt",typeof(Text).Name }, {"img",typeof(Image).Name } };

根据名字去获取组件的类型
因此我们需要确定组件的命名格式,然后根据命名来确认类型
初始化: xxx_but=trtransform.Find("路径").GetComponent<组件类型>()
我们需要获取物体的路径
/// /// 获取物体的路径 /// /// /// static string GetgameObjectPath(Transform go) { string path = ""; while (go != Selection.gameobjects[0]) {path = path.Insert(0, "/"); path = path.Insert(0, go.name); go = go.parent; } return path; }

创建一个类来保存定义组件,初始化和销毁代码的字符串
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIInfo { private string file1; private string body1; private string body2; public string File1 { get { return file1; } set { file1 = value; } }public string Body1 { get { return body1; } set { body1 = value; } }public string Body2 { get { return body2; } set { body2 = value; } } //构造函数,补全代码块(file1, body1, body2) public UIInfo(string name, string contrastKey, string path) { file1 = string.Format("public {0} {1}", GetUIPath.typMap[contrastKey], name); body1 = string.Format("{0} =transform.Find(\"{1}\").GetComponent<{2}>()", name, path, GetUIPath.typMap[contrastKey]); body2 = string.Format("{0}=null", name); }}

将所有的组件的名字,组件类型,路径储存到List中
/// /// 获取物体的基本信息(名字,校准key,路径),并储存 /// /// static void GetChildinfo(Transform tf) { Debug.Log(tf.name); foreach (Transform tfChild in tf) {string contrastKey = tfChild.name.Substring(0, 3); if (typMap.ContainsKey(contrastKey)) { Debug.Log(tfChild.name + "------" + contrastKey + "------" + GetgameObjectPath(tfChild)); UIInfo uinf = new UIInfo(tfChild.name, contrastKey, GetgameObjectPath(tfChild)); uinfo.Add(uinf); } if (tfChild.childCount >= 0) { GetChildinfo(tfChild); } }}

然后将模板程序中相应的地方替换成list中的代码,并保存文件
private static string File1 = ""; private static string Body1 = ""; static void WriteScript() {for (int i = 0; i < uinfo.Count; i++) { File1 += uinfo[i].File1 + "; \r\n"; Body1 += uinfo[i].Body1 + "; \r\n"; Debug.Log(uinfo[i].File1 + "_____________" + uinfo[i].Body1 + "______________" + uinfo[i].Body2); } Debug.Log(File1 + "---------------" + Body1); Eg_str = Eg_str.Replace("@File1", File1); Eg_str = Eg_str.Replace("@Body1", Body1); //储存文档 SaveFileDialog saveFile = new SaveFileDialog(); saveFile.FileName = "TestName.cs"; string path = Environment.CurrentDirectory.Replace("/", @"\"); if (saveFile.ShowDialog() == DialogResult.OK) { string[] name = saveFile.FileName.Split('\\'); string nameStr = name[name.Length - 1].Replace(".cs", ""); Eg_str = Eg_str.Replace("@Name", nameStr); File.WriteAllText(saveFile.FileName, Eg_str); } }

最后在给unity编辑器写个命令创建出相应的脚步
[MenuItem("MyTools/GetScript")] static void CreatScript() { GameObject[] select = Selection.gameObjects; if (select.Length == 1) { Transform selectGo = select[0].transform; GetChildinfo(selectGo); WriteScript(); } else { EditorUtility.DisplayDialog("警告", "你只能选择一个GameObject", "确定"); }}

完整的代码
GetUIPath.cs
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using UnityEngine.UI; using System.Windows.Forms; using Application = UnityEngine.Application; using Button = UnityEngine.UI.Button; using MenuItem = UnityEditor.MenuItem; /* 注意事项:UI命名规则 Button: but_xxx; Text: txt_xxx; Image: img_xxx; */ public class GetUIPath : Editor {public static Dictionary typMap = new Dictionary() { {"but",typeof(Button).Name }, {"txt",typeof(Text).Name }, {"img",typeof(Image).Name } }; private static List uinfo = new List(); private static string Eg_str = "using System.Collections; " + "\r\nusing System.Collections.Generic; " + "\r\nusing UnityEngine; \r\tusing UnityEngine.UI; " + "\r\n//Wait for me, I don\'t want to let you down\r\n" + "//love you into disease, but no medicine can.\r\n" + "//Created By HeXiaoTao\r\n" + "public class @Name : MonoBehaviour {\r\n\r\n\t" + "@File1// Use this for initialization\r\n\tvoid Start () {@Body1}\r\n\t\r\n\t" + "// Update is called once per frame\r\n\tvoid Update () {\r\n\t\t\r\n\t}\r\n" + "}"; private static string File1 = ""; private static string Body1 = ""; static void WriteScript() {for (int i = 0; i < uinfo.Count; i++) { File1 += uinfo[i].File1 + "; \r\n"; Body1 += uinfo[i].Body1 + "; \r\n"; Debug.Log(uinfo[i].File1 + "_____________" + uinfo[i].Body1 + "______________" + uinfo[i].Body2); } Debug.Log(File1 + "---------------" + Body1); Eg_str = Eg_str.Replace("@File1", File1); Eg_str = Eg_str.Replace("@Body1", Body1); //储存文档 SaveFileDialog saveFile = new SaveFileDialog(); saveFile.FileName = "TestName.cs"; string path = Environment.CurrentDirectory.Replace("/", @"\"); if (saveFile.ShowDialog() == DialogResult.OK) { string[] name = saveFile.FileName.Split('\\'); string nameStr = name[name.Length - 1].Replace(".cs", ""); Eg_str = Eg_str.Replace("@Name", nameStr); File.WriteAllText(saveFile.FileName, Eg_str); } } /// /// 获取物体的路径 /// /// /// static string GetgameObjectPath(Transform go) { string path = ""; while (go != Selection.gameobjects[0]) {path = path.Insert(0, "/"); path = path.Insert(0, go.name); go = go.parent; } return path; } /// /// 获取物体的基本信息(名字,校准key,路径),并储存 /// /// static void GetChildinfo(Transform tf) { Debug.Log(tf.name); foreach (Transform tfChild in tf) {string contrastKey = tfChild.name.Substring(0, 3); if (typMap.ContainsKey(contrastKey)) { Debug.Log(tfChild.name + "------" + contrastKey + "------" + GetgameObjectPath(tfChild)); UIInfo uinf = new UIInfo(tfChild.name, contrastKey, GetgameObjectPath(tfChild)); uinfo.Add(uinf); } if (tfChild.childCount >= 0) { GetChildinfo(tfChild); } }}[MenuItem("MyTools/GetScript")] static void CreatScript() { GameObject[] select = Selection.gameObjects; if (select.Length == 1) { Transform selectGo = select[0].transform; GetChildinfo(selectGo); WriteScript(); } else { EditorUtility.DisplayDialog("警告", "你只能选择一个GameObject", "确定"); }} }

【unity获取UI组件结构的小工具】UIInfo.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIInfo { private string file1; private string body1; private string body2; public string File1 { get { return file1; } set { file1 = value; } }public string Body1 { get { return body1; } set { body1 = value; } }public string Body2 { get { return body2; } set { body2 = value; } } public UIInfo(string name, string contrastKey, string path) { file1 = string.Format("public {0} {1}", GetUIPath.typMap[contrastKey], name); body1 = string.Format("{0} =transform.Find(\"{1}\").GetComponent<{2}>()", name, path, GetUIPath.typMap[contrastKey]); body2 = string.Format("{0}=null", name); }}

实现的效果 选择对应的ui组件,点击编辑器下的MyTools/GetScript

unity获取UI组件结构的小工具
文章图片
image.png unity获取UI组件结构的小工具
文章图片
image.png
最终效果

unity获取UI组件结构的小工具
文章图片
image.png 结束 Over

    推荐阅读