Unity生成简易代码工具

C#代码,可以自己编辑下,只要有规律,可以改成Lua的Panel代码,手写代码易错.特蛋痛的是lua写错编辑器还不报错
效果图
代码如下

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Text;
using System.IO;

public class ZSXGenerateCodeWindow : EditorWindow
{
    [MenuItem("Helps/生成初始代码")]
    public static void OpenWindow()
    {
        if (codeWindow == null)
            codeWindow = EditorWindow.GetWindow(typeof(ZSXGenerateCodeWindow)) as ZSXGenerateCodeWindow;
        codeWindow.Show();
    }

    private static ZSXGenerateCodeWindow codeWindow = null;
    //选择的根游戏体
    private GameObject root;

    void OnGUI()
    {
        DrawSelectUI();
        DrawFindWidget();
    }

    /// <summary>
    /// 绘制 选择要分析的UI
    /// </summary>
    private void DrawSelectUI()
    {
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("把Prefab拖到Hierarchy面板,Hierarchy面板的Prefab拖入UI框中,选中物体,选择要使用的组件");//, GUILayout.Width(100));
        using (EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope())
        {
            EditorGUILayout.LabelField("选择待处理UI:", GUILayout.Width(100));
            root = EditorGUILayout.ObjectField(root, typeof(GameObject), true) as GameObject;
        }
    }

    /// <summary>
    /// 绘制 查找UI控件
    /// </summary>
    private void DrawFindWidget()
    {
        EditorGUILayout.Space();
        using (EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope())
        {
            GUI.backgroundColor = Color.white;
            Rect rect = hScope.rect;
            rect.height = EditorGUIUtility.singleLineHeight;
            GUI.Box(rect, "");

            if (GUILayout.Button(" copy 组件属性 "))
            {
                GUIUtility.systemCopyBuffer = string.Join("\r\n", mAttributes);
            }

            if (GUILayout.Button(" copy 生成路径 "))
            {
                GUIUtility.systemCopyBuffer = string.Join("\r\n", mFinds);
            }
            if (GUILayout.Button(" copy 属性+路径 "))
            {
                var tt = string.Join("\r\n", mAttributes) + "\r\n" + string.Join("\r\n", mFinds);
                GUIUtility.systemCopyBuffer = tt;
            }
            if (GUILayout.Button(" 清空 "))
            {
                mFinds.Clear();
                mAttributes.Clear();
            }
        }
        Repaint();
        if (Selection.activeGameObject == null || root == null) return;
        var mComponents = Selection.activeGameObject.GetComponents<Component>();
        using (EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope())
        {
            GUI.backgroundColor = Color.white;
            Rect rect = hScope.rect;
            EditorGUILayout.LabelField("有以下的组件",GUILayout.Width(110));

            for (int i = 0; i < mComponents.Length; i++)
            {
                var tCom = mComponents[i];
                GenerateCode(tCom, root.transform);
            }
        }

        using (EditorGUILayout.VerticalScope hScope = new EditorGUILayout.VerticalScope())
        {
            GUI.backgroundColor = Color.white;
            Rect rect = hScope.rect;           
            var tGenUI = string.Format(@"using UnityEngine.UI;
using UnityEngine;
public class {0} : MonoBehaviour
    {{
       {1}
        void Awake()
        {{
          {2}
        }}
    }}
",root.name, string.Join("\r\n       ", mAttributes), string.Join("\r\n          ", mFinds));

            int height = 140;
            if (mAttributes.Count > 0)
                height = mAttributes.Count * 15 + mFinds.Count * 15 + 110;

            if (GUILayout.Button("生成脚本__"+root.name))
            {
                CreateCsUIScript(tGenUI);
            }
            EditorGUILayout.LabelField(tGenUI, GUILayout.Height(height));
        }
    }

    List<string> mAttributes = new List<string>();
    List<string> mFinds = new List<string>();

    string FindPath(Transform pParent, Transform pSelect)
    {
        if (pParent == null)
        {
            Debug.LogError("父 路径空了");
            return "";
        }
        if (pSelect == null)
        {
            Debug.LogError("选中 路径空了");
            return "";
        }

        var tStr = "";
        Transform temp = pSelect;
        for (int i = 0; i < 10; i++)
        {
            if (temp.transform == pParent)
            {
                break;
            }
            else
            {
                tStr = temp.transform.name + "/" + tStr;
                temp = temp.transform.parent;
            }
        }
        return "\"" + (tStr.TrimEnd('/')) + "\"";
    }

    void GenerateCode(Component tCom, Transform tPrefab)
    {
        var tGoName = tCom.gameObject.name;//挂件名(自己起的)
        var tTypeName = tCom.GetType().Name;//组件名
        if (tTypeName.Equals("CanvasRenderer")) return;
        var styleHas = new GUIStyle(GUI.skin.button);
        styleHas.normal.textColor = Color.red;
        var tAttName = tGoName + "_" + tTypeName;//将生成属性名

        var transStr = "private " + tTypeName + " " + tAttName + ";";
        var findStr =  tAttName + "=transform.Find(" + FindPath(tPrefab, tCom.transform) + ").GetComponent<" + tCom.GetType().Name + ">();";
        if (mAttributes.Contains(transStr) == false)
        {
            if (GUILayout.Button(tTypeName))
            {
                mAttributes.Add(transStr);
                mFinds.Add(findStr);
            }
        }
        else if (GUILayout.Button(tTypeName, styleHas))
        {
            mAttributes.Remove(transStr);
            mFinds.Remove(findStr);
        }
    }
    /// <summary>
    /// 生成C# UI脚本
    /// </summary>
    private void CreateCsUIScript(string pStr)
    {
        string path = EditorPrefs.GetString("create_script_folder", "");
        path = EditorUtility.SaveFilePanel("Create Script", path, root.name + ".cs", "cs");
        if (string.IsNullOrEmpty(path)) return;

        File.WriteAllText(path, pStr, new UTF8Encoding(false));
        AssetDatabase.Refresh();
        EditorPrefs.SetString("create_script_folder", path);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值