自动生成脚本代码_可扩展

这是一个Unity编辑器扩展脚本,用于根据选择的UI对象自动生成带有组件标识的C#脚本。用户可以选择不同的UI元素类型,如Root、Transform、Button、Text等,脚本会自动为每个组件创建私有变量并初始化它们。生成的脚本包含了Awake和Start方法,方便在游戏对象上直接使用。
摘要由CSDN通过智能技术生成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Text;
using System.IO;

public class MyScriptCreat : Editor
{

    private static string ScriptsFolderPath = Application.dataPath + "/Scripts"; //脚本文件夹路径

    //key: 组件类型 value: 脚本列表
    private static Dictionary<ModuleSignType, List<UIModuleSign>> DataDic = new Dictionary<ModuleSignType, List<UIModuleSign>>();

    private static StringBuilder m_BuilderVariable = new StringBuilder(); //变量
    private static StringBuilder m_BuilderCommonFunc = new StringBuilder(); //公共方法
    private static StringBuilder m_BuilderComponent = new StringBuilder(); //路径


    #region MenuItem
    [MenuItem("GameObject/ScriptTools/AddSign/UI_Root", priority = 0)]
    public static void AddSignUIRoot()
    {
        AddSignScript(ModuleSignType.Root);
    }

    [MenuItem("GameObject/ScriptTools/AddSign/UI_Transform", priority = 0)]
    public static void AddSignUITransform()
    {
        AddSignScript(ModuleSignType.Transform);
    }
    [MenuItem("GameObject/ScriptTools/AddSign/UI_GameObject", priority = 0)]
    public static void AddSignUIGameObject()
    {
        AddSignScript(ModuleSignType.GameObject);
    }
    [MenuItem("GameObject/ScriptTools/AddSign/UI_Button", priority = 0)]
    public static void AddSignUIButton()
    {
        AddSignScript(ModuleSignType.Button);
    }
    [MenuItem("GameObject/ScriptTools/AddSign/UI_Text", priority = 0)]
    public static void AddSignUIText()
    {
        AddSignScript(ModuleSignType.Text);
    }
    [MenuItem("GameObject/ScriptTools/AddSign/UI_Image", priority = 0)]
    public static void AddSignUIImage()
    {
        AddSignScript(ModuleSignType.Image);
    }

    [MenuItem("GameObject/ScriptTools/CreatUIScript")]
    public static void CreatUIScript()
    {
        if (Selection.gameObjects == null || Selection.gameObjects.Length == 0)
        {
            EditorUtility.DisplayDialog("Error", "请选中一个Root节点,再进行该操作","OK");
            return;
        }
        GameObject go = Selection.gameObjects[0];
        UIModuleSign sign = go.GetComponent<UIModuleSign>();
        if (sign == null || sign.SignType != ModuleSignType.Root)
        {
            EditorUtility.DisplayDialog("Error", "该节点非Root节点,请先选择Root节点,再进行该操作", "OK");
            return;
        }
        GetAllSignAndModule(go.transform);
        string scriptName = go.name;
        StringBuilder builderVariable = AppendAllData(scriptName);
        //
        WriteData(builderVariable.ToString(),scriptName);
        AssetDatabase.Refresh();
    }
    #endregion

    //添加标识脚本
    static void AddSignScript(ModuleSignType theSignType)
    {
        if (Selection.gameObjects == null || Selection.gameObjects.Length<1)
        {
            return;
        }
        int count = Selection.gameObjects.Length;
        for (int i = 0; i < count; i++)
        {
            GameObject go = Selection.gameObjects[i];
            UIModuleSign script = TryAddComponent<UIModuleSign>(go);
            script.SignType = theSignType;
        }
    }

    private static T TryAddComponent<T>(GameObject theTarget)where T: Component
    {
        T t = theTarget.GetComponent<T>();
        if (t==null)
        {
            t = theTarget.AddComponent<T>();
        }
        return t;
    }

    //按类型添加脚本到字典中
    private static void GetAllSignAndModule(Transform theRoot)
    {
        DataDic.Clear();
        List<UIModuleSign> moduleList = new List<UIModuleSign>();
        theRoot.GetComponentsInChildren(moduleList);
        moduleList.Sort((a, b) =>
        {
            return a.SignType.CompareTo(b.SignType);
        });
        List<UIModuleSign> outList = null;
        foreach (UIModuleSign item in moduleList)
        {
            if (item.SignType == ModuleSignType.Root)
                continue;
            DataDic.TryGetValue(item.SignType, out outList);
            if (outList == null)
            {
                outList = new List<UIModuleSign>();
                DataDic[item.SignType] = outList;
            }
            //Debug.Log(item.RelativePath);
            //Debug.Log(item.SignType.ToString());
            DataDic[item.SignType].Add(item);
        }
    }

    #region AppentData

    //拼接全部内容
    private static StringBuilder AppendAllData(string theScriptName)
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.AppendLine("using UnityEngine;");
        stringBuilder.AppendLine("using UnityEngine.UI;");
        stringBuilder.AppendLine("using System;");
        stringBuilder.AppendLine("");
        stringBuilder.Append("public class ");
        stringBuilder.Append(theScriptName);
        stringBuilder.Append(" : MonoBehaviour");
        stringBuilder.AppendLine();
        stringBuilder.AppendLine("{");
        //
        AppendVariable();   //变量
        AppendUnityMethod();    //公共方法
        AppendInitComponent();  //初始化组件
        stringBuilder.AppendLine(m_BuilderVariable.ToString());
        stringBuilder.AppendLine(m_BuilderCommonFunc.ToString());
        stringBuilder.AppendLine(m_BuilderComponent.ToString());
        //
        stringBuilder.AppendLine("}");
        return stringBuilder;
    }

    //拼接变量
    private static void AppendVariable()
    {
        m_BuilderVariable.Clear();
        if (DataDic != null && DataDic.Count > 0)
        {
            foreach (ModuleSignType signType in DataDic.Keys)
            {
                m_BuilderVariable.AppendLine();
                m_BuilderVariable.AppendLine("    #region " + signType.ToString());
                List<UIModuleSign> signList = DataDic[signType];
                foreach (UIModuleSign item in signList)
                {
                    //变量
                    m_BuilderVariable.Append("    ");
                    m_BuilderVariable.Append("private ");
                    m_BuilderVariable.Append(signType.ToString() + " ");
                    m_BuilderVariable.Append(item.GameName + ";");
                    m_BuilderVariable.AppendLine();
                }
                m_BuilderVariable.AppendLine("    #endregion ");
            }
        }
    }

    //拼接公共方法
    private static void AppendUnityMethod()
    {
        m_BuilderCommonFunc.Clear();
        m_BuilderCommonFunc.AppendLine();
        #region Awake__InitComponent
        m_BuilderCommonFunc.Append("    private void Awake()");
        m_BuilderCommonFunc.AppendLine();
        m_BuilderCommonFunc.AppendLine("    {");
        m_BuilderCommonFunc.AppendLine("        InitComponent();");
        m_BuilderCommonFunc.AppendLine("    }");
        #endregion
        #region Start
        m_BuilderCommonFunc.AppendLine();
        m_BuilderCommonFunc.Append("    private void Start()");
        m_BuilderCommonFunc.AppendLine();
        m_BuilderCommonFunc.AppendLine("    {");
        m_BuilderCommonFunc.AppendLine();
        m_BuilderCommonFunc.AppendLine("    }");
        #endregion
    }

    //初始化组件
    private static void AppendInitComponent()
    {
        m_BuilderComponent.Clear();
        if (DataDic != null && DataDic.Count > 0)
        {
            m_BuilderComponent.AppendLine();
            m_BuilderComponent.Append("    private void InitComponent()");
            m_BuilderComponent.AppendLine();
            m_BuilderComponent.AppendLine("    {");
            foreach (ModuleSignType signType in DataDic.Keys)
            {
                m_BuilderComponent.AppendLine("        #region " + signType.ToString());
                List<UIModuleSign> signList = DataDic[signType];
                foreach (UIModuleSign item in signList)
                {
                    //路径
                    m_BuilderComponent.Append("        " + item.GameName + " = ");
                    m_BuilderComponent.Append("transform.Find(\"" + item.RelativePath + "\")");
                    m_BuilderComponent.AppendLine(".GetComponent<" + signType.ToString() + ">();");
                }
                m_BuilderComponent.AppendLine("        #endregion ");
            }
            m_BuilderComponent.AppendLine("    }");
        }
    }

    #endregion

    //写入数据
    private static void WriteData(string theContent,string theFileName)
    {
        if (string.IsNullOrEmpty(theContent))
        {
            return;
        }
        string filePath = EditorUtility.SaveFilePanelInProject("选择脚本保存路径",theFileName,"cs","message", ScriptsFolderPath);
        filePath = filePath.Replace("Assets","");
        filePath = Application.dataPath + filePath;
        if (!File.Exists(filePath))
        {
            FileStream fs = File.Create(filePath);
            fs.Close();
            fs = null;
        }
        File.WriteAllText(filePath, theContent,Encoding.UTF8);
    }
}

标识脚本

using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// UI组件标识脚本
/// </summary>
public class UIModuleSign : MonoBehaviour
{
    public ModuleSignType SignType = ModuleSignType.Transform;

    /// <summary>
    /// 对象名称
    /// </summary>
    public string GameName
    {
        get { return gameObject.name; }
    }

    private string m_RelativePath;

    /// <summary>
    /// 相对于Root节点的相对路径
    /// </summary>
    public string RelativePath
    {
        get 
        {
            m_RelativePath = "";
            RelativePathByRoot(transform);
            return m_RelativePath;
        }
    }

    //Root节点的相对路径
    private void RelativePathByRoot(Transform theTrans)
    {
        if (theTrans == null)
        {
            return;
        }
        UIModuleSign sign = theTrans.GetComponent<UIModuleSign>();
        if (sign!=null && sign.SignType == ModuleSignType.Root)
        {
            return;
        }
        m_RelativePath = string.IsNullOrEmpty(m_RelativePath) ? theTrans.name : theTrans.name + "/" + m_RelativePath;
        RelativePathByRoot(theTrans.parent);
    }
}
//UI组件标识类型
public enum ModuleSignType
{
    Root = 1,
    Transform,
    GameObject,
    Button,
    Text,
    Image,
}

生成后的脚本示例:

using UnityEngine;
using UnityEngine.UI;
using System;

public class UIPanel : MonoBehaviour
{
    #region Transform
    private Transform Trans;
    #endregion 

    #region Button
    private Button BtnCancel;
    private Button BtnOK;
    #endregion 

    #region Text
    private Text LabTItle;
    #endregion 

    #region Image
    private Image ImgTop;
    #endregion 
    
    private void Awake()
    {
        InitComponent();
    }

    private void Start()
    {

    }
    
    private void InitComponent()
    {
        #region Transform
        Trans = transform.Find("Bg/Trans").GetComponent<Transform>();
        #endregion 
        #region Button
        BtnCancel = transform.Find("Bg/BtnCancel").GetComponent<Button>();
        BtnOK = transform.Find("Bg/BtnOK").GetComponent<Button>();
        #endregion 
        #region Text
        LabTItle = transform.Find("Bg/LabTItle").GetComponent<Text>();
        #endregion 
        #region Image
        ImgTop = transform.Find("Bg/ImgTop").GetComponent<Image>();
        #endregion 
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值