using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
using System.Text;
using System;
using System.IO;
using System.Reflection;
///
/// 描述:编辑器插件,快速生成UI代码(只检索以特定文本开头的组件,img_图片 btn_按钮 txt_文本)
/// 作者:WJ
///
public class QuickUI
{
///
/// UI的根游戏体
///
private static GameObject mRoot = null;
///
/// ui控件列表
///
private static List mUIWidgets = new List();
///
/// 缓存所有变量名和对应控件对象,对重名作处理
///
private static Dictionary mVariableNameDic = new Dictionary();
///
/// 组件名称检索列表(只检索以列表开头命名的组件)
///
private static List mWidgetsNameSearchList = new List { "btn_", "img_", "txt_" };
///
/// 组件类型检索列表(只检索里的组件)
///
private static List mWidgetsTypeSearchList = new List { "Button", "Image", "Text" };
///
/// 变量编号
///
private static int mVariableNum = 0;
///
/// 变量代码
///
private static StringBuilder mCodeStateText = null;
///
/// 事件代码
///
private static StringBuilder mCodeEventText = null;
///
/// 初始化变量代码
///
private static StringBuilder mCodeAssignText = null;
///
/// 开始函数
///
private static StringBuilder mStartText = null;
///
/// 更新函数
///
private static StringBuilder mUpdateText = null;
///
/// 函数注释
///
private static string funNotes = "\n\t/// \n\t/// {0}\n\t/// ";
///
/// 生成UI代码
///
[MenuItem("Tools/GenerateUICode")]
public static void GenerateUICode()
{
// 自动赋值选中的GameObject
mRoot = Selection.activeGameObject;
if (mRoot == null)
{
Debug.LogError("未选中UI根节点");
return;
}
// 创建开始函数
StartFunCode();
// 创建更新函数
UpdateFunCode();
// 查找UI组件
FindUIWidgets();
// 生成UI组件变量
GenerateVariable();
// 给UI组件变量赋值
AssignmentVariable();
// 给UI组件绑定事件
BuildEventCode();
// 生成脚本
CreateUIScript();
}
///
/// 查找UI组件
///
private static void FindUIWidgets()
{
// 查找节点下所有UI元素
RecursiveUI(mRoot.transform, (tran) =>
{
UIBehaviour[] widgets = tran.GetComponents();
for (int i = 0; i < widgets.Length; i++)
{
var widget = widgets[i];
if (widget != null && !mUIWidgets.Contains(widget))
{
// 只检测特定类型
Type type = widget.GetType();
if (mWidgetsTypeSearchList.Contains(type.Name) == false)
{
continue;
}
// 图片组件中有按钮,则不添加
if (type.Name == "Image")
{
Button button = widget.GetComponent