AlicizaX/Client/Packages/com.alicizax.unity.ui/Editor/UIConfig/ScriptGenerator.cs
2025-01-24 16:21:00 +08:00

957 lines
37 KiB
C#

#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using AlicizaX.UI.Runtime;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace AlicizaX.UI.Editor
{
internal static class ScriptGenerator
{
private static UIGenerateGlobalSettings m_GenerateGlobalSetting;
public static string UIGenerateGlobalSettingPath = $"Assets/AlicizaFramework/UISetting/UIGenerateGlobalSettings.asset";
const string RegisterUIHelper = "Assets/GameScripts/HotFix/GameLogic/Runtime/UI";
const string RegisterUIHelperMain = "Assets/GameScripts/Main/Launcher/Scripts";
#region
//Bind文件存放根路径
const string BindComponetsSavePath = "Assets/GameScripts/HotFix/GameLogic/Runtime/UI/BindComponents";
//界面逻辑文件存放根路径
const string UILogicSavePath = "Assets/GameScripts/HotFix/GameLogic/Runtime/UI/View";
//预制体存放根路径
const string UIPrefabSavePath = "Assets/AssetRaw/UI";
public const string HotfixNameSpace = "GameLogic.UI";
#endregion
#region
//Bind文件存放根路径
const string BindComponetsMainSavePath = "Assets/GameScripts/Main/Launcher/Scripts/UI/BindComponents";
//界面逻辑文件存放根路径
const string UILogicMainSavePath = "Assets/GameScripts/Main/Launcher/Scripts/UI/View";
//预制体存放根路径
const string UIPrefabMainSavePath = "Assets/GameScripts/Main/Launcher/Resources";
public const string MainNameSpace = "GameMain.UI";
#endregion
static string WindowPrefabSavePath = Path.Combine(UIPrefabSavePath, "UIWindow");
static string WidgetPrefabSavePath = Path.Combine(UIPrefabSavePath, "UIWidget");
static string ViewPrefabSavePath = Path.Combine(UIPrefabSavePath, "UIView");
static string WindowBindSavePath = Path.Combine(BindComponetsSavePath, "Window");
static string WidgetBindSavePath = Path.Combine(BindComponetsSavePath, "Widget");
static string ViewBindSavePath = Path.Combine(BindComponetsSavePath, "View");
static string WindowLogicSavePath = Path.Combine(UILogicSavePath, "Window");
static string WidgetLogicSavePath = Path.Combine(UILogicSavePath, "Widget");
static string ViewLogicSavePath = Path.Combine(UILogicSavePath, "View");
static string ScriptsNameSpace = "GameLogic.UI";
static void SwitchHotFitRootPath(UIBindComponent bindComponent)
{
bool isHotfix = bindComponent.ResLoadType == EUIResLoadType.AssetBundle;
WindowPrefabSavePath = Path.Combine(isHotfix ? UIPrefabSavePath : UIPrefabMainSavePath, "UIWindow");
WidgetPrefabSavePath = Path.Combine(isHotfix ? UIPrefabSavePath : UIPrefabMainSavePath, "UIWidget");
ViewPrefabSavePath = Path.Combine(isHotfix ? UIPrefabSavePath : UIPrefabMainSavePath, "UIView");
WindowBindSavePath = Path.Combine(isHotfix ? BindComponetsSavePath : BindComponetsMainSavePath, "Window");
WidgetBindSavePath = Path.Combine(isHotfix ? BindComponetsSavePath : BindComponetsMainSavePath, "Widget");
ViewBindSavePath = Path.Combine(isHotfix ? BindComponetsSavePath : BindComponetsMainSavePath, "View");
WindowLogicSavePath = Path.Combine(isHotfix ? UILogicSavePath : UILogicMainSavePath, "Window");
WidgetLogicSavePath = Path.Combine(isHotfix ? UILogicSavePath : UILogicMainSavePath, "Widget");
ViewLogicSavePath = Path.Combine(isHotfix ? UILogicSavePath : UILogicMainSavePath, "View");
ScriptsNameSpace = isHotfix ? HotfixNameSpace : MainNameSpace;
}
static void GenerateUIRegisterHelper(Assembly assembly, string path)
{
// 获取程序集中的所有类型
var types = assembly.GetTypes();
List<Type> eventTypes = new List<Type>();
// 遍历每个类型
foreach (Type type in types)
{
// 检查类型是否是接口
if (type.IsInterface)
{
continue;
}
var attribute = Attribute.GetCustomAttribute(type, typeof(WindowAttribute)) as WindowAttribute;
if (attribute != null)
{
eventTypes.Add(type);
}
}
var filePath = Path.Combine(path, "UIRegisterHelper.cs");
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.WriteLine("using AlicizaFramework;");
sw.WriteLine($"namespace {ScriptsNameSpace}");
sw.WriteLine("{");
sw.WriteLine("\tpublic static class UIRegisterHelper");
sw.WriteLine("\t{");
sw.WriteLine("\t\tpublic static void Initlize()");
sw.WriteLine("\t\t{\n");
foreach (var type in eventTypes)
{
sw.WriteLine($"\t\t\tUICacheRegister.Register<{type.FullName}>();\n");
}
sw.WriteLine("\t\t}");
sw.WriteLine("\t}");
sw.WriteLine("}");
}
}
static void GenerateUIRegisterHelper()
{
// Assembly mainAssembly = Assembly.GetAssembly(typeof(DisStripCode));
// GenerateUIRegisterHelper(mainAssembly, RegisterUIHelperMain);
//
// Assembly hotfixAssembly = Assembly.GetAssembly(typeof(GameLogic.GameModule));
// GenerateUIRegisterHelper(hotfixAssembly, RegisterUIHelper);
}
public static UIGenerateGlobalSettings UIGenerateGlobalSetting
{
get
{
if (m_GenerateGlobalSetting == null)
{
m_GenerateGlobalSetting = AssetDatabase.LoadAssetAtPath<UIGenerateGlobalSettings>(UIGenerateGlobalSettingPath);
}
return m_GenerateGlobalSetting;
}
}
public static void GenerateUIPanelScript(UIBindComponent uiBindComponent)
{
SwitchHotFitRootPath(uiBindComponent);
uiBindComponent.ScriptName = uiBindComponent.gameObject.name;
if (uiBindComponent.ResLoadType == EUIResLoadType.Resources)
{
uiBindComponent.Location = "UI" + uiBindComponent.UIType + "/" + uiBindComponent.gameObject.name;
}
else
{
uiBindComponent.Location = uiBindComponent.gameObject.name;
}
if (uiBindComponent.UIType == UIType.Window)
{
SaveAllChildWidgets(uiBindComponent);
CreateUIScript(uiBindComponent);
CreateWndUIPrefab(uiBindComponent);
}
else
{
CreateUIWidgetScript(uiBindComponent);
CreateWidgetUIPrefab(uiBindComponent);
}
GenerateUIRegisterHelper();
AssetDatabase.Refresh();
}
private static void SaveAllChildWidgets(UIBindComponent uiBindComponent)
{
List<UIBindComponent> childWidgets = new List<UIBindComponent>();
CheckIsSaveWidget(uiBindComponent.transform, ref childWidgets);
string CombineName = "包含多个组件\n";
foreach (var VARIABLE in childWidgets)
{
CombineName += VARIABLE.ScriptName + "\n";
}
if (childWidgets.Count > 0)
{
bool result = EditorUtility.DisplayDialog(
"Hello!", // 标题
CombineName, // 消息内容
"一起生成保存", // 确认按钮
"不保存子组件" // 取消按钮(可选)
);
if (result)
{
foreach (var VARIABLE in childWidgets)
{
BindComponent(VARIABLE);
GenerateUIPanelScript(VARIABLE);
}
}
}
}
private static void CheckIsSaveWidget(Transform root, ref List<UIBindComponent> childWidegt)
{
for (int i = 0; i < root.childCount; ++i)
{
Transform child = root.GetChild(i);
if (child.name.IndexOf("widget", StringComparison.OrdinalIgnoreCase) >= 0)
{
UIBindComponent childWd = child.GetComponent<UIBindComponent>();
if (childWd == null)
{
Debug.Log("Widget 不包含UIBindComponent 命名不正确" + child.name);
}
if (childWd && string.IsNullOrEmpty(childWd.ScriptName))
{
Debug.Log("Widget 生成脚本名不正确 检查UIBindComponent " + child.name);
}
if (childWd && !string.IsNullOrEmpty(childWd.ScriptName))
{
childWidegt.Add(childWd);
}
continue;
}
CheckIsSaveWidget(child, ref childWidegt);
}
}
#region UIView
private static void CreateUIViewScript(UIBindComponent uiBindComponent)
{
string logicFilePath = Path.Combine(ViewLogicSavePath, uiBindComponent.ScriptName + ".cs");
string bindFilePath = Path.Combine(ViewBindSavePath, uiBindComponent.ScriptName + ".BindComponents.cs");
string LogicText = GetWidgetLogicText(uiBindComponent);
string bindText = GetWidgetBingComponentLogicText(uiBindComponent);
if (!Directory.Exists(ViewBindSavePath))
{
Directory.CreateDirectory(ViewBindSavePath);
}
if (!Directory.Exists(ViewLogicSavePath))
{
Directory.CreateDirectory(ViewLogicSavePath);
}
File.WriteAllText(bindFilePath, bindText);
File.WriteAllText(logicFilePath, LogicText);
}
public static void CreateWidgetUIPrefab(UIBindComponent uiBindComponent)
{
string prefabPath = Path.Combine(WidgetPrefabSavePath, uiBindComponent.ScriptName + ".prefab");
if (!Directory.Exists(WidgetPrefabSavePath))
{
Directory.CreateDirectory(WidgetPrefabSavePath);
}
if (File.Exists(prefabPath))
{
File.Delete(prefabPath);
}
if (uiBindComponent.gameObject)
{
RectTransform rectTransform = uiBindComponent.gameObject.GetComponent<RectTransform>();
if (rectTransform != null)
{
// 修改RectTransform的锚点
rectTransform.localScale = Vector3.one;
}
}
PrefabUtility.SaveAsPrefabAsset(uiBindComponent.gameObject, prefabPath);
Debug.Log($"{uiBindComponent.ScriptName} Generate Succesd");
}
#endregion
#region UIWidget
private static void CreateUIWidgetScript(UIBindComponent uiBindComponent)
{
string logicFilePath = Path.Combine(WidgetLogicSavePath, uiBindComponent.ScriptName + ".cs");
string bindFilePath = Path.Combine(WidgetBindSavePath, uiBindComponent.ScriptName + ".BindComponents.cs");
string LogicText = GetWidgetLogicText(uiBindComponent);
string bindText = GetWidgetBingComponentLogicText(uiBindComponent);
if (!Directory.Exists(WidgetBindSavePath))
{
Directory.CreateDirectory(WidgetBindSavePath);
}
if (!Directory.Exists(WidgetLogicSavePath))
{
Directory.CreateDirectory(WidgetLogicSavePath);
}
File.WriteAllText(bindFilePath, bindText);
File.WriteAllText(logicFilePath, LogicText);
}
public static void CreateViewUIPrefab(UIBindComponent uiBindComponent)
{
string prefabPath = Path.Combine(ViewPrefabSavePath, uiBindComponent.ScriptName + ".prefab");
if (!Directory.Exists(ViewPrefabSavePath))
{
Directory.CreateDirectory(ViewPrefabSavePath);
}
if (File.Exists(prefabPath))
{
File.Delete(prefabPath);
}
if (uiBindComponent.gameObject)
{
RectTransform rectTransform = uiBindComponent.gameObject.GetComponent<RectTransform>();
if (rectTransform != null)
{
// 修改RectTransform的锚点
rectTransform.localScale = Vector3.one;
}
}
PrefabUtility.SaveAsPrefabAsset(uiBindComponent.gameObject, prefabPath);
Debug.Log($"{uiBindComponent.ScriptName} Generate Succesd");
}
private static string GetWidgetLogicText(UIBindComponent uiBindComponent)
{
string logicFilePath = Path.Combine(WidgetLogicSavePath, uiBindComponent.ScriptName + ".cs");
string logicRef = "";
if (File.Exists(logicFilePath))
{
logicRef = File.ReadAllText(logicFilePath);
}
StringBuilder logicTextBuilder = new StringBuilder();
var hasLogic = logicRef.Length > 0;
if (!hasLogic)
{
logicTextBuilder.Append("using UnityEngine;\n");
logicTextBuilder.Append("using AlicizaFramework;\n\n");
logicTextBuilder.Append($"namespace {ScriptsNameSpace}\n");
logicTextBuilder.Append("{\n");
logicTextBuilder.Append("\tpublic partial class " + uiBindComponent.ScriptName + " \n");
logicTextBuilder.Append("\t{\n");
logicTextBuilder.Append("\n");
logicTextBuilder.Append("\t\t#region UIBind事件\n");
logicTextBuilder.Append(GetCallBackText(uiBindComponent, logicRef));
logicTextBuilder.Append("\n");
logicTextBuilder.Append("\t\t#endregion\n\n");
logicTextBuilder.Append("\n\t}\n");
logicTextBuilder.Append("}\n");
}
else
{
int index = logicRef.ToString().IndexOf("UIBind事件");
if (index != -1)
{
logicTextBuilder.Append(logicRef.Insert(index + 8,
"\n" + GetCallBackText(uiBindComponent, logicRef)));
}
else
{
Debug.LogError("请检查该脚本自动生成关键字#region UIBind事件是否被去除!");
}
}
return logicTextBuilder.ToString();
}
private static string GetWidgetBingComponentLogicText(UIBindComponent uiBindComponent)
{
StringBuilder bindComponetsBuilder = new StringBuilder();
bindComponetsBuilder.Append(GetRefrenceNameSpace(uiBindComponent));
bindComponetsBuilder.Append($"using AlicizaFramework;\n");
bindComponetsBuilder.Append($"namespace {ScriptsNameSpace}\n");
bindComponetsBuilder.Append("{\n");
bindComponetsBuilder.Append("\tpublic partial class " + uiBindComponent.ScriptName + $" : UIWidget\n");
bindComponetsBuilder.Append("\t{\n");
// 脚本工具生成的代码
bindComponetsBuilder.Append("\t\t#region 脚本工具生成的代码\n");
bindComponetsBuilder.Append(GetVarText(uiBindComponent));
bindComponetsBuilder.Append("\t\tprotected override void OnBindUIComponents()\n");
bindComponetsBuilder.Append("\t\t{\n");
bindComponetsBuilder.Append("\t\t\tInitBindComponent();\n");
bindComponetsBuilder.Append(GetBindText(uiBindComponent));
bindComponetsBuilder.Append(GetBindUIEvent(uiBindComponent));
bindComponetsBuilder.Append("\t\t}\n");
bindComponetsBuilder.Append("\t\t#endregion");
bindComponetsBuilder.Append("\n\t}\n");
bindComponetsBuilder.Append("}\n");
return bindComponetsBuilder.ToString();
}
#endregion
public static void CreateWndUIPrefab(UIBindComponent uiBindComponent)
{
string prefabPath = Path.Combine(WindowPrefabSavePath, uiBindComponent.ScriptName + ".prefab");
if (!Directory.Exists(WindowPrefabSavePath))
{
Directory.CreateDirectory(WindowPrefabSavePath);
}
if (File.Exists(prefabPath))
{
File.Delete(prefabPath);
}
if (uiBindComponent.gameObject)
{
var prefabClone = GameObject.Instantiate(uiBindComponent.gameObject, uiBindComponent.transform.parent);
prefabClone.name = uiBindComponent.ScriptName;
RemoveChildWidget(prefabClone.transform);
RectTransform rectTransform = prefabClone.gameObject.GetComponent<RectTransform>();
if (rectTransform != null)
{
// 修改RectTransform的锚点
rectTransform.pivot = new Vector2(0.5f, 0.5f);
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
rectTransform.offsetMin = Vector2.zero;
rectTransform.offsetMax = Vector2.zero;
rectTransform.localScale = Vector3.one;
// rectTransform.anchoredPosition = Vector2.zero;
// rectTransform.position = Vector3.zero;
}
PrefabUtility.SaveAsPrefabAsset(prefabClone.gameObject, prefabPath);
Debug.Log($"{uiBindComponent.ScriptName} Generate Succesd");
Object.DestroyImmediate(prefabClone);
}
}
private static void RemoveChildWidget(Transform root)
{
for (int i = 0; i < root.childCount; ++i)
{
Transform child = root.GetChild(i);
if (child.name.IndexOf("widget", StringComparison.OrdinalIgnoreCase) >= 0)
{
Debug.Log("包含子Widget 移除保存" + child.name);
GameObject.DestroyImmediate(child.gameObject);
continue;
}
RemoveChildWidget(child);
}
}
private static void CreateUIScript(UIBindComponent uiBindComponent)
{
string logicFilePath = Path.Combine(WindowLogicSavePath, uiBindComponent.ScriptName + ".cs");
string bindFilePath = Path.Combine(WindowBindSavePath, uiBindComponent.ScriptName + ".BindComponents.cs");
string LogicText = GetUILogicText(uiBindComponent);
string bindText = GetUIBingComponentLogicText(uiBindComponent);
string attributeResText = $"[UIRes(location: \"{uiBindComponent.Location}\" , EUIResLoadType.{uiBindComponent.ResLoadType})]\n";
string attributeText = $"\t[Window(UILayer.{uiBindComponent.UILayer}, fullScreen:{uiBindComponent.FullScreen.ToString().ToLower()} , delayedClose:{uiBindComponent.CacheDuration.ToString()})]\n";
bindText = bindText.Replace("#AttributeMark", attributeResText + attributeText);
if (!Directory.Exists(WindowBindSavePath))
{
Directory.CreateDirectory(WindowBindSavePath);
}
if (!Directory.Exists(WindowLogicSavePath))
{
Directory.CreateDirectory(WindowLogicSavePath);
}
File.WriteAllText(bindFilePath, bindText);
File.WriteAllText(logicFilePath, LogicText);
}
private static string GetUILogicText(UIBindComponent uiBindComponent,
bool isHotfixProject = true)
{
string logicFilePath = Path.Combine(WindowLogicSavePath, uiBindComponent.ScriptName + ".cs");
string logicRef = "";
if (File.Exists(logicFilePath))
{
logicRef = File.ReadAllText(logicFilePath);
}
StringBuilder logicTextBuilder = new StringBuilder();
var hasLogic = logicRef.Length > 0;
if (!hasLogic)
{
logicTextBuilder.Append("using UnityEngine;\n");
logicTextBuilder.Append("using AlicizaFramework;\n\n");
logicTextBuilder.Append($"namespace {ScriptsNameSpace}\n");
logicTextBuilder.Append("{\n");
logicTextBuilder.Append("\tpartial class " + uiBindComponent.ScriptName + " \n");
logicTextBuilder.Append("\t{\n");
logicTextBuilder.Append("\n");
logicTextBuilder.Append("\t\t#region UIBind事件\n");
logicTextBuilder.Append(GetCallBackText(uiBindComponent, logicRef));
logicTextBuilder.Append("\n");
logicTextBuilder.Append("\t\t#endregion\n\n");
logicTextBuilder.Append(GetLogicLifeText(uiBindComponent));
logicTextBuilder.Append("\n\t}\n");
logicTextBuilder.Append("}\n");
}
else
{
int index = logicRef.ToString().IndexOf("UIBind事件");
if (index != -1)
{
logicTextBuilder.Append(logicRef.Insert(index + 8,
"\n" + GetCallBackText(uiBindComponent, logicRef)));
}
else
{
logicTextBuilder.Append(logicRef.ToString());
Debug.LogWarning("该脚本自动生成关键字#region UIBind事件被去除 不进行追加UI事件");
}
}
return logicTextBuilder.ToString();
}
/// <summary>
/// 构建部分类 xxxUI.BindComponetns
/// </summary>
/// <param name="uiBindComponent"></param>
/// <param name="isHotfixProject"></param>
/// <returns></returns>
private static string GetUIBingComponentLogicText(UIBindComponent uiBindComponent, bool isHotfixProject = true)
{
StringBuilder bindComponetsBuilder = new StringBuilder();
bindComponetsBuilder.Append(GetRefrenceNameSpace(uiBindComponent));
bindComponetsBuilder.Append($"using AlicizaFramework;\n");
bindComponetsBuilder.Append($"namespace {ScriptsNameSpace}\n");
bindComponetsBuilder.Append("{\n");
bindComponetsBuilder.Append("\t#AttributeMark");
bindComponetsBuilder.Append("\tpartial class " + uiBindComponent.ScriptName + " : UIWindow\n");
bindComponetsBuilder.Append("\t{\n");
// 脚本工具生成的代码
bindComponetsBuilder.Append("\t\t#region 脚本工具生成的代码\n");
bindComponetsBuilder.Append(GetVarText(uiBindComponent));
bindComponetsBuilder.Append("\t\tprotected override void OnBindUIComponents()\n");
bindComponetsBuilder.Append("\t\t{\n");
bindComponetsBuilder.Append("\t\t\tInitBindComponent();\n");
bindComponetsBuilder.Append(GetBindText(uiBindComponent));
bindComponetsBuilder.Append(GetBindUIEvent(uiBindComponent));
bindComponetsBuilder.Append("\t\t}\n");
bindComponetsBuilder.Append("\t\t#endregion");
bindComponetsBuilder.Append("\n\t}\n");
bindComponetsBuilder.Append("}\n");
return bindComponetsBuilder.ToString();
}
/// <summary>
/// 获取所有组件的对应命名空间引用
/// </summary>
/// <param name="uiBindComponent"></param>
/// <returns></returns>
private static string GetRefrenceNameSpace(UIBindComponent uiBindComponent)
{
StringBuilder refrenceNameSpaceBuilder = new StringBuilder();
List<string> nameSpaces = new List<string>();
for (int i = 0; i < uiBindComponent.bindComponents.Count; i++)
{
var nameSpace = uiBindComponent.Elements[i].BindCom.GetType().Namespace;
if (!nameSpaces.Contains(nameSpace))
{
nameSpaces.Add(nameSpace);
refrenceNameSpaceBuilder.Append($"using {nameSpace};\n");
}
}
return refrenceNameSpaceBuilder.ToString();
}
/// <summary>
/// 获取所有绑定组件的引用
/// </summary>
/// <param name="uiBindComponent"></param>
/// <returns></returns>
private static string GetBindText(UIBindComponent uiBindComponent)
{
StringBuilder bindTextBuilder = new StringBuilder();
for (int i = 0; i < uiBindComponent.bindComponents.Count; i++)
{
var varName = uiBindComponent.Elements[i].Name;
var varType = uiBindComponent.Elements[i].BindCom.GetType().Name;
switch (varType)
{
case "GameObject":
bindTextBuilder.Append(
$"\t\t\t{varName} = FChild<{varType}>({i}).gameObject;\n");
break;
case "RichItemIcon":
bindTextBuilder.Append(
$"\t\t\t{varName} = CreateWidgetByType<{varType}>(FChild(\"{varName}\"));\n");
break;
case "RedNoteWidget":
break;
case "TextButtonItem":
case "SwitchTabItem":
case "UIActorWidget":
case "UIEffectWidget":
case "UISpineWidget":
case "UIMainPlayerWidget":
bindTextBuilder.Append(
$"\t\t\t{varName} = CreateWidget<{varType}>(FChild(\"{varName}\").gameObject);\n");
break;
default:
bindTextBuilder.Append(
$"\t\t\t{varName} = FChild<{varType}>({i});\n");
break;
}
}
return bindTextBuilder.ToString();
}
/// <summary>
/// 获取所有组件的引用
/// </summary>
/// <param name="uiBindComponent"></param>
/// <returns></returns>
private static string GetVarText(UIBindComponent uiBindComponent)
{
StringBuilder varTextBuilder = new StringBuilder();
for (int i = 0; i < uiBindComponent.bindComponents.Count; i++)
{
var varName = uiBindComponent.Elements[i].Name;
varTextBuilder.Append("\t\tprivate " + uiBindComponent.Elements[i].BindCom.GetType().Name + " " + varName + ";\n");
}
return varTextBuilder.ToString();
}
/// <summary>
/// 获取所有组件的绑定事件
/// </summary>
/// <param name="uiBindComponent"></param>
/// <returns></returns>
private static string GetBindUIEvent(UIBindComponent uiBindComponent)
{
StringBuilder bingUIEventBuilder = new StringBuilder();
for (int i = 0; i < uiBindComponent.bindComponents.Count; i++)
{
var varName = uiBindComponent.Elements[i].SplitName;
var comName = uiBindComponent.Elements[i].Name;
var varType = uiBindComponent.Elements[i].BindCom.GetType().Name;
if (varType == "Button" || varType == "UIButtonSuper" || varType == "UIButtonSuperText")
{
string varFuncName = GetBtnFuncName(varName);
bingUIEventBuilder.Append($"\t\t\t{comName}.onClick.AddListener({varFuncName});\n");
}
else if (varType == "Toggle")
{
string varFuncName = GetToggleFuncName(varName);
bingUIEventBuilder.Append($"\t\t\t{comName}.onValueChanged.AddListener({varFuncName});\n");
}
else if (varType == "Slider")
{
string varFuncName = GetSliderFuncName(varName);
bingUIEventBuilder.Append($"\t\t\t{comName}.onValueChanged.AddListener({varFuncName});\n");
}
}
return bingUIEventBuilder.ToString();
}
/// <summary>
/// 获取所有组件的绑定回调
/// </summary>
/// <param name="uiBindComponent"></param>
/// <param name="logicRef"></param>
/// <returns></returns>
private static string GetCallBackText(UIBindComponent uiBindComponent, string logicRef)
{
StringBuilder callBackText = new StringBuilder();
for (int i = 0; i < uiBindComponent.bindComponents.Count; i++)
{
var varName = uiBindComponent.Elements[i].SplitName;
var varType = uiBindComponent.Elements[i].BindCom.GetType().Name;
if (varType == "Button" || varType == "UIButtonSuper" || varType == "UIButtonSuperText")
{
string varFuncName = GetBtnFuncName(varName);
if (!logicRef.Contains(varFuncName))
{
callBackText.Append($"\t\tprivate void {varFuncName}()\n");
callBackText.Append("\t\t{\n\t\t}\n");
}
}
else if (varType == "Toggle")
{
string varFuncName = GetToggleFuncName(varName);
if (!logicRef.Contains(varFuncName))
{
callBackText.Append($"\t\tprivate void {varFuncName}(bool isOn)\n");
callBackText.Append("\t\t{\n\t\t}\n");
}
}
else if (varType == "Slider")
{
string varFuncName = GetSliderFuncName(varName);
if (!logicRef.Contains(varFuncName))
{
callBackText.Append($"\t\tprivate void {varFuncName}(float valFue)\n");
callBackText.Append("\t\t{\n\t\t}\n");
}
}
}
return callBackText.ToString();
}
/// <summary>
/// 构建脚本生命周期
/// </summary>
/// <param name="uiBindComponent"></param>
/// <returns></returns>
private static string GetLogicLifeText(UIBindComponent uiBindComponent)
{
StringBuilder lifeTextBuilder = new StringBuilder();
//觉得还是没有必要加 需要哪个自己override吧
// lifeTextBuilder.Append("\t\t#region 生命周期事件\n");
// lifeTextBuilder.Append($"\t\tprotected override void OnInitlize()\n");
// lifeTextBuilder.Append("\t\t{\n");
// lifeTextBuilder.Append("\t\t\tbase.OnInitlize();\n");
// lifeTextBuilder.Append("\t\t}\n");
// lifeTextBuilder.Append($"\t\tprotected override void OnOpen()\n");
// lifeTextBuilder.Append("\t\t{\n");
// lifeTextBuilder.Append("\t\t\tbase.OnOpen();\n");
// lifeTextBuilder.Append("\t\t}\n");
// lifeTextBuilder.Append($"\t\tprotected override void OnUpdate()\n");
// lifeTextBuilder.Append("\t\t{\n");
// lifeTextBuilder.Append("\t\t\tbase.OnUpdate();\n");
// lifeTextBuilder.Append("\t\t}\n");
// lifeTextBuilder.Append($"\t\tprotected override void OnClose()\n");
// lifeTextBuilder.Append("\t\t{\n");
// lifeTextBuilder.Append("\t\t\tbase.OnClose();\n");
// lifeTextBuilder.Append("\t\t}\n");
// lifeTextBuilder.Append($"\t\tprotected override void OnDispose()\n");
// lifeTextBuilder.Append("\t\t{\n");
// lifeTextBuilder.Append("\t\t\tbase.OnDispose();\n");
// lifeTextBuilder.Append("\t\t}\n");
// lifeTextBuilder.Append("\t\t#endregion\n\n");
return lifeTextBuilder.ToString();
}
/// <summary>
/// 绑定组件
/// </summary>
/// <param name="bindComponent"></param>
public static void BindComponent(UIBindComponent bindComponent)
{
List<UIBindComponent.UIBindData> bindDatas = new List<UIBindComponent.UIBindData>();
CollectComponet(bindComponent.transform, ref bindDatas);
bindComponent.bindComponents.Clear();
foreach (var bindData in bindDatas)
{
bindComponent.bindComponents.Add(bindData.BindCom);
}
bindComponent.Elements = bindDatas;
}
/// <summary>
/// 收集组件
/// </summary>
/// <param name="root"></param>
/// <param name="bingDatas"></param>
private static void CollectComponet(Transform root, ref List<UIBindComponent.UIBindData> bingDatas)
{
for (int i = 0; i < root.childCount; ++i)
{
Transform child = root.GetChild(i);
if (child.name.IndexOf("widget", StringComparison.OrdinalIgnoreCase) >= 0)
{
Debug.Log("包含子Widget 如非Widget组件 请避开命名 路径" + child.name);
continue;
}
string[] comArray = SplitComName(child.name);
if (comArray != null)
{
string splitName = child.name.Substring(child.name.IndexOf("@") + 1);
foreach (var com in comArray)
{
var typeName = GetVerType(com);
var component = child.GetComponent(typeName);
var keyName = GetKeyName(com, child.name);
if (bingDatas.Find(a => a.Name == keyName) != null)
{
Debug.LogError("有重复的key:" + keyName);
continue;
}
if (component == null)
{
Debug.LogError($"{child.name}没有{typeName}组件");
continue;
}
bingDatas.Add(new UIBindComponent.UIBindData(keyName, component, splitName));
}
}
CollectComponet(child, ref bingDatas);
}
}
private static string[] SplitComName(string name)
{
bool hasCom = name.Contains("@");
if (!hasCom) return null;
string comStr = name.Substring(0, name.IndexOf("@"));
string[] comArray = comStr.Split("#");
return comArray;
}
private static string GetKeyName(string comName, string Key)
{
return $"m{comName}{Key.Substring(Key.IndexOf("@") + 1)}";
}
/// <summary>
/// 情况所有组件
/// </summary>
/// <param name="bindComponent"></param>
public static void ClearBindComponets(UIBindComponent bindComponent)
{
bindComponent.bindComponents.Clear();
bindComponent.Elements.Clear();
}
/// <summary>
/// 清楚空引用
/// </summary>
/// <param name="bindComponent"></param>
public static void ClearNullRefrence(UIBindComponent bindComponent)
{
for (var index = bindComponent.Elements.Count - 1; index >= 0; index--)
{
if (bindComponent.Elements[index].BindCom == null)
{
bindComponent.Elements.RemoveAt(index);
}
}
bindComponent.bindComponents.Clear();
foreach (var VARIABLE in bindComponent.Elements)
{
bindComponent.bindComponents.Add(VARIABLE.BindCom);
}
}
private static string GetBtnFuncName(string varName)
{
return $"OnBtn{varName}Click";
}
private static string GetToggleFuncName(string varName)
{
return "OnToggle" + varName + "Change";
}
private static string GetSliderFuncName(string varName)
{
return "OnSlider" + varName + "Change";
}
private static string GetVerType(string uiName)
{
foreach (var pair in UIGenerateGlobalSetting.scriptGenerateRule)
{
if (uiName.StartsWith(pair.uiElementRegex))
{
return pair.componentName;
}
}
return string.Empty;
}
private static string GetUIBindDataPrefix(string uiName)
{
foreach (var pair in UIGenerateGlobalSetting.scriptGenerateRule)
{
if (uiName.StartsWith(pair.uiElementRegex))
{
return pair.uiElementRegex;
}
}
return string.Empty;
}
}
}
#endif