Unity生成简易代码工具(Lua脚本)

在这里插入图片描述

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

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

    private static ZSXLuaGenerateCodeWindow 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", mFinds.ToArray());
            }
            if (GUILayout.Button(" 清空 "))
            {
                mFinds.Clear();
            }
        }

        Repaint();
        if (Selection.activeGameObject == null || root == null) return;

        using (EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope())
        {
            GUI.backgroundColor = Color.white;
            Rect rect = hScope.rect;
            EditorGUILayout.LabelField("有以下的组件", GUILayout.Width(110));
            GenerateCode(Selection.activeGameObject, root.transform, true);
            GenerateCode(Selection.activeGameObject, root.transform, false);
        }

        using (EditorGUILayout.VerticalScope hScope = new EditorGUILayout.VerticalScope())
        {
            GUI.backgroundColor = Color.white;
            Rect rect = hScope.rect;
            var tGenUI = string.Format(@"local transform;
local gameObject;
{0}Panel = {{}};
local this = {0};

--启动事件--
function {0}.Awake(obj)
	gameObject = obj;
	transform = obj.transform;
	this.InitPanel();	
end

--初始化面板--
function {0}.InitPanel()
    {1}
end

--单击事件--
function {0}.OnDestroy()
end
", root.name, string.Join("\r\n    ", mFinds.ToArray()));

            int height = 340;
            if (mFinds.Count > 0)
                height = mFinds.Count * 15 + 310;

            if (GUILayout.Button("生成脚本Panel_" + root.name))
            {
                CreateLuaPanelScript(tGenUI);
            }
            if (GUILayout.Button("生成脚本Ctrl_" + root.name.Replace("Panel", "Ctrl")))
            {
                CreateLuaCtrlScript();
            }
            EditorGUILayout.LabelField(tGenUI, GUILayout.Height(height));
        }
    }
    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(GameObject pGo, Transform tRoot, bool isGo)
    {
        var tGoName = pGo.gameObject.name;//挂件名(自己起的)
        var tTypeName = pGo.GetType().Name;//组件名
        if (tTypeName.Equals("CanvasRenderer")) return;
        var styleHas = new GUIStyle(GUI.skin.button);
        styleHas.normal.textColor = Color.red;
        var path = FindPath(tRoot, pGo.transform);

        if (isGo)//gameObject
        {
            var findStrGo = string.Format("this.{0} = transform:Find({1}).gameObject;", tGoName, path);
            if (mFinds.Contains(findStrGo) == false)
            {
                if (GUILayout.Button("GameObject"))
                {
                    mFinds.Add(findStrGo);
                }
            }
            else if (GUILayout.Button("GameObject", styleHas))
            {
                mFinds.Remove(findStrGo);
            }
        }
        else//Transform
        {
            var findStrTr = string.Format("this.{0}_Tr = transform:Find({1});", tGoName, path);
            if (mFinds.Contains(findStrTr) == false)
            {
                if (GUILayout.Button("Transform"))
                {
                    mFinds.Add(findStrTr);
                }
            }
            else if (GUILayout.Button("Transform", styleHas))
            {
                mFinds.Remove(findStrTr);
            }
        }
    }
    /// <summary>
    /// 生成C# UI脚本
    /// </summary>
    private void CreateLuaPanelScript(string pStr)
    {
        string path = EditorPrefs.GetString("create_script_folder", "");
        path = EditorUtility.SaveFilePanel("Create Script", path, root.name + ".lua", "lua");
        if (string.IsNullOrEmpty(path)) return;

        File.WriteAllText(path, pStr, new UTF8Encoding(false));
        AssetDatabase.Refresh();
        EditorPrefs.SetString("create_script_folder", path);
        Debug.Log(root.name + " 成功");
    }
    void CreateLuaCtrlScript()
    {
        string vT = @"{0}Ctrl={{}}
local this={0}Ctrl;
local transform
local gameObject
local {1}

function {0}Ctrl.New()
    return this
end

function {0}Ctrl.Awake()
    panelMgr:CreatePanel({2},this.OnCreate)
end

function {0}Ctrl.OnCreate(obj)
    gameObject = obj
    {1}=gameObject:GetComponent({3})
    --自己写上
end

function {0}Ctrl.OnClick(go)
  destroy(gameObject)
end

function {0}Ctrl.Close()
   panelMgr:ClosePanel(CtrlNames.{0})
end";

        string path = EditorPrefs.GetString("create_script_folder", "");
        path = EditorUtility.SaveFilePanel("Create Script", path, root.name.Replace("Panel", "Ctrl.lua"), "lua");

        if (string.IsNullOrEmpty(path)) return;
        var v0 = root.name.Replace("Panel", "");
        var v1 = v0.ToLower();
        var v2 = "\"" + v0 + "\"";
        var v3 = "\"LuaBehaviour\"";
        var LuaStr = string.Format(vT, v0, v1, v2, v3);

        File.WriteAllText(path, LuaStr, new UTF8Encoding(false));
        AssetDatabase.Refresh();
        EditorPrefs.SetString("create_script_folder", path);
        Debug.Log(v0 + "Ctrl 成功");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值