找回密码
 立即注册
查看: 375|回复: 0

[笔记] Unity UI组件代码自动生成工具

[复制链接]
发表于 2022-4-14 14:07 | 显示全部楼层 |阅读模式
先看效果




2.需要资源:
ViewElementModel.txt
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using GersonFrame.UI;

namespace DragonRun
{
    public class {0} : ViewElementBase
    {
                {1}
        public override void InitElement(GameObject go)
        {
                        {2}
        }
    }
}
ViewElementEditor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;

public class ViewElementEditor : EditorWindow
{
    public string CsFilePath = "/HotFix_Dragon~/UI_Hot/ViewElement/";
    public string ViewMudelFilePath = "Assets/GersonFrame/UIManager/Editor/ViewElementModel.txt";
    private GameObject m_viewGoRoot;
    private string GetCompentStr = "GetComponent<{0}>();\n";
    private bool m_click;


    private List<string> m_properityList = new List<string>();
    private List<string> m_getCompentList = new List<string>();


    private SerializedObject m_obj;
    private SerializedProperty m_CsFilePath;

    [MenuItem("MyTools/创建ViewElement数据")]
    static void ShowEditor()
    {
        ViewElementEditor combinewindow = GetWindow<ViewElementEditor>();
        combinewindow.minSize = new Vector2(370, 370);
     
    }

    private void OnEnable()
    {
        MyDebuger.InitLogger( LogLevel.All);
           m_click = false;
           m_obj =  new SerializedObject(this);
        m_CsFilePath = m_obj.FindProperty("CsFilePath");
    }


    private void OnGUI()
    {
        BeginWindows();
        m_obj.Update();
        EditorGUI.BeginChangeCheck();
        EditorGUILayout.PropertyField(m_CsFilePath,true);
        if (EditorGUI.EndChangeCheck())
        {
            m_obj.ApplyModifiedProperties();
        }
        EditorGUILayout.LabelField("View根节点:");
        m_viewGoRoot = (GameObject)EditorGUILayout.ObjectField(m_viewGoRoot, typeof(GameObject), true);
        this.m_click = GUILayout.Button("创建");
        EndWindows();
        if (m_click)
        {
            this.m_click = false;
            if (m_viewGoRoot == null)
            {
                MyDebuger.LogError("View根节点不能为空 ");
                return;
            }
            CreateViewElemnet();
        }
    }


    void CreateViewElemnet()
    {
        m_properityList.Clear();
        m_getCompentList.Clear();
        TextAsset basestrTxt = AssetDatabase.LoadAssetAtPath<TextAsset>(ViewMudelFilePath);
        string basestr = basestrTxt.text;
        string allpropertity = "";
        string allgetCompent = "";
        FindGoChild(m_viewGoRoot.transform);
        if (m_properityList.Count < 1) {
            MyDebuger.LogError("未找可生成的组件物体");
            return;
        }
      
        m_click = true;
        for (int i = 0; i < this.m_properityList.Count; i++)
            allpropertity += this.m_properityList;
        for (int i = 0; i < this.m_getCompentList.Count; i++)
            allgetCompent += this.m_getCompentList;
        string elementName = m_viewGoRoot.name+ "ViewElement";
        string newbasestr = basestr.Replace("{0}", elementName);
        newbasestr= newbasestr.Replace("{1}", allpropertity);
        string newbasestr2 = newbasestr.Replace("{2}", allgetCompent);

        string filepath = Application.dataPath + CsFilePath + elementName + ".cs";

        if (File.Exists(filepath)) File.Delete(filepath);

        using (FileStream fs = new FileStream(filepath,FileMode.OpenOrCreate))
        {
            using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8))
            {
                sw.Write(newbasestr2);
            }
        }
        MyDebuger.Log("创建 "+elementName +"成功!");
        AssetDatabase.Refresh();
    }


    void FindGoChild(Transform ts)
    {
        TsNeedAddInViewElement(ts);
        for (int i = 0; i < ts.childCount; i++)
        {
            FindGoChild(ts.GetChild(i));
        }
    }



    void TsNeedAddInViewElement(Transform childts)
    {
        string properitystr = "";
        string tempgetCompentstr = "";
        string properityName = "m_" + childts.name;
        if (childts.name.Contains("_Txt"))
        {
            tempgetCompentstr= GetCompentStr.Replace("{0}", "Text");
            properitystr = "public Text "+ properityName+";\n";

        }
        else if (childts.name.Contains("_Btn"))
        {
            tempgetCompentstr = GetCompentStr.Replace("{0}", "Button");
            properitystr = "public Button " + properityName + ";\n";
        }
        else if (childts.name.Contains("_RawImg"))
        {
            tempgetCompentstr = GetCompentStr.Replace("{0}", "RawImage");
            properitystr = "public RawImage " + properityName + ";\n";
        }
        else if (childts.name.Contains("_Img"))
        {
            tempgetCompentstr = GetCompentStr.Replace("{0}", "Image");
            properitystr = "public Image " + properityName + ";\n";
        }
        else if (childts.name.Contains("_Ts"))
        {
            tempgetCompentstr = GetCompentStr.Replace("{0}", "Transform");
            properitystr = "public Transform " + properityName + ";\n";
        }
        else if (childts.name.Contains("_RectTs"))
        {
            tempgetCompentstr = GetCompentStr.Replace("{0}", "RectTransform");
            properitystr = "public RectTransform " + properityName + ";\n";
        }
        if (!string.IsNullOrEmpty(properitystr))
        {
            m_properityList.Add(properitystr);
            string path = childts.GetPath(m_viewGoRoot.transform);
            string tempgetCompentNameStr = properityName+"=go.transform.Find(" + '"' + path+ '"' + ").";
            m_getCompentList.Add(tempgetCompentNameStr+tempgetCompentstr);
        }
     
    }

}
ViewElementBase.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace GersonFrame.UI
{

    /// <summary>
    ///  一个物体结尾为_Txt 需要自动生成Text组件
    ///  一个物体结尾为_Btn 需要自动生成Button组件
    ///一个物体结尾为_RawImg 需要自动生成RawImage组件
    ///一个物体结尾为_Img 需要自动生成Image组件
    ///一个物体结尾为_Ts 需要自动生成Transform组件
    /// 一个物体结尾为_RectTs 需要自动生成RectTransform组件
    /// </summary>
    public class ViewElementBase
    {

        public virtual void InitElement(GameObject go)
        {

        }

    }
}
VS工程自动添加生成的文件方法如下(此处要感谢群里的小伙伴的提示):
1.找到vs工程的csproj这个文件,使用文本编辑器打开 找到一堆include的目录地方
2.添加UI生成文件的指定目标 然后加上*.cs


3.删除原有生成的所有在UI生成文件夹下的Include标记
4.点击解决方案的刷新按钮


5.效果如图



具体用法在脚本中有哈 什么问题欢迎留言

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-4-29 02:14 , Processed in 0.123825 second(s), 27 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表