com.alicizax.unity.framework/Editor/UI/Helper/UIScriptGeneratorHelper.cs

631 lines
25 KiB
C#
Raw Normal View History

2025-09-05 19:46:30 +08:00
using System;
2025-11-11 10:57:35 +08:00
using System.Collections;
2025-09-05 19:46:30 +08:00
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using AlicizaX.UI.Editor;
using AlicizaX.UI.Runtime;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
2025-11-10 16:01:53 +08:00
using UnityEditor.SceneManagement;
2025-09-05 19:46:30 +08:00
2025-11-07 20:47:57 +08:00
namespace AlicizaX.UI.Editor
{
2025-11-11 10:57:35 +08:00
public enum EBindType
{
None,
Widget,
ListCom,
}
2025-09-05 19:46:30 +08:00
[Serializable]
2025-11-11 10:57:35 +08:00
internal class UIBindData
2025-09-05 19:46:30 +08:00
{
public string Name;
public List<Component> BindCom;
public EBindType BindType;
public UIBindData(string name, List<Component> bindCom, EBindType bindType = EBindType.None)
{
2025-11-11 10:57:35 +08:00
Name = name ?? throw new ArgumentNullException(nameof(name));
BindCom = bindCom ?? new List<Component>();
2025-09-05 19:46:30 +08:00
BindType = bindType;
}
public UIBindData(string name, Component bindCom, EBindType bindType = EBindType.None)
2025-11-11 10:57:35 +08:00
: this(name, new List<Component> { bindCom }, bindType)
2025-09-05 19:46:30 +08:00
{
}
}
2025-09-10 14:26:54 +08:00
internal static class UIScriptGeneratorHelper
2025-09-05 19:46:30 +08:00
{
private static UIGenerateConfiguration _uiGenerateConfiguration;
2025-11-10 16:01:53 +08:00
private static IUIGeneratorRuleHelper _uiGeneratorRuleHelper;
2025-11-07 20:47:57 +08:00
2025-11-11 10:57:35 +08:00
private static List<UIBindData> _uiBindDatas = new List<UIBindData>();
private static HashSet<string> _arrayComponents = new HashSet<string>(StringComparer.Ordinal);
2025-11-10 16:01:53 +08:00
public static IUIGeneratorRuleHelper UIGeneratorRuleHelper
2025-11-07 20:47:57 +08:00
{
get
{
2025-11-11 10:57:35 +08:00
if (_uiGeneratorRuleHelper == null ||
(_uiGeneratorRuleHelper != null && !UIConfiguration.UIScriptGeneratorRuleHelper.Equals(_uiGeneratorRuleHelper.GetType().FullName, StringComparison.Ordinal)))
2025-11-07 20:47:57 +08:00
{
2025-11-11 10:57:35 +08:00
var ruleHelperTypeName = UIConfiguration.UIScriptGeneratorRuleHelper;
if (string.IsNullOrWhiteSpace(ruleHelperTypeName))
{
Debug.LogError("UIScriptGeneratorHelper: UIScriptGeneratorRuleHelper not configured.");
return null;
}
Type ruleHelperType = Type.GetType(ruleHelperTypeName);
2025-11-07 20:47:57 +08:00
if (ruleHelperType == null)
{
2025-11-11 10:57:35 +08:00
Debug.LogError($"UIScriptGeneratorHelper: Could not load UI ScriptGeneratorHelper {ruleHelperTypeName}");
2025-11-07 20:47:57 +08:00
return null;
}
2025-11-10 16:01:53 +08:00
_uiGeneratorRuleHelper = Activator.CreateInstance(ruleHelperType) as IUIGeneratorRuleHelper;
2025-11-11 10:57:35 +08:00
if (_uiGeneratorRuleHelper == null)
{
Debug.LogError($"UIScriptGeneratorHelper: Failed to instantiate {ruleHelperTypeName} as IUIGeneratorRuleHelper.");
}
2025-11-07 20:47:57 +08:00
}
2025-09-05 19:46:30 +08:00
2025-11-10 16:01:53 +08:00
return _uiGeneratorRuleHelper;
2025-11-07 20:47:57 +08:00
}
}
private static UIGenerateConfiguration UIConfiguration
2025-09-05 19:46:30 +08:00
{
get
{
if (_uiGenerateConfiguration == null)
{
_uiGenerateConfiguration = UIGenerateConfiguration.Instance;
}
return _uiGenerateConfiguration;
}
}
2025-11-07 20:47:57 +08:00
private static string GetVersionType(string uiName)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
if (string.IsNullOrEmpty(uiName)) return string.Empty;
foreach (var pair in UIConfiguration.UIElementRegexConfigs ?? Enumerable.Empty<UIEelementRegexData>())
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
if (string.IsNullOrEmpty(pair?.uiElementRegex)) continue;
2025-11-07 20:47:57 +08:00
if (uiName.StartsWith(pair.uiElementRegex, StringComparison.Ordinal))
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
return pair.componentType ?? string.Empty;
2025-09-05 19:46:30 +08:00
}
}
return string.Empty;
}
2025-11-07 20:47:57 +08:00
private static string[] SplitComponentName(string name)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
if (string.IsNullOrEmpty(name)) return null;
var common = UIConfiguration.UIGenerateCommonData;
if (string.IsNullOrEmpty(common?.ComCheckEndName) || !name.Contains(common.ComCheckEndName))
return null;
int endIndex = name.IndexOf(common.ComCheckEndName, StringComparison.Ordinal);
if (endIndex <= 0) return null;
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
string comStr = name.Substring(0, endIndex);
string split = common.ComCheckSplitName ?? "#";
// 使用 string[] 重载并移除空项,防止错误 overload
return comStr.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);
2025-09-05 19:46:30 +08:00
}
2025-11-07 20:47:57 +08:00
private static string GetKeyName(string key, string componentName, EBindType bindType)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
var helper = UIGeneratorRuleHelper;
if (helper == null)
throw new InvalidOperationException("UIGeneratorRuleHelper is not configured.");
return helper.GetPrivateComponentByNameRule(key, componentName, bindType);
2025-09-05 19:46:30 +08:00
}
private static void GetBindData(Transform root)
{
2025-11-11 10:57:35 +08:00
if (root == null) return;
2025-09-05 19:46:30 +08:00
for (int i = 0; i < root.childCount; ++i)
{
Transform child = root.GetChild(i);
2025-11-11 10:57:35 +08:00
if (child == null) continue;
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
// 排除关键字
if (UIConfiguration.UIGenerateCommonData.ExcludeKeywords != null &&
UIConfiguration.UIGenerateCommonData.ExcludeKeywords.Any(k =>
!string.IsNullOrEmpty(k) && child.name.IndexOf(k, StringComparison.OrdinalIgnoreCase) >= 0))
{
2025-11-07 20:47:57 +08:00
continue;
2025-11-11 10:57:35 +08:00
}
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
bool hasWidget = child.GetComponent<UIHolderObjectBase>() != null;
bool isArrayComponent = !string.IsNullOrEmpty(UIConfiguration.UIGenerateCommonData.ArrayComSplitName) &&
child.name.StartsWith(UIConfiguration.UIGenerateCommonData.ArrayComSplitName, StringComparison.Ordinal);
2025-11-07 20:47:57 +08:00
if (hasWidget)
2025-09-05 19:46:30 +08:00
{
CollectWidget(child);
}
2025-11-07 20:47:57 +08:00
else if (isArrayComponent)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
// 提取 array 标识文本(例如 "*Item*0" -> "Item"
2025-11-07 20:47:57 +08:00
string splitCode = UIConfiguration.UIGenerateCommonData.ArrayComSplitName;
2025-11-11 10:57:35 +08:00
int firstIndex = child.name.IndexOf(splitCode, StringComparison.Ordinal);
2025-11-07 20:47:57 +08:00
int lastIndex = child.name.LastIndexOf(splitCode, StringComparison.Ordinal);
2025-11-11 10:57:35 +08:00
if (firstIndex < 0 || lastIndex <= firstIndex) continue;
// 中间文本
string text = child.name.Substring(firstIndex + splitCode.Length, lastIndex - (firstIndex + splitCode.Length));
if (string.IsNullOrEmpty(text)) continue;
2025-11-07 20:47:57 +08:00
if (_arrayComponents.Contains(text)) continue;
_arrayComponents.Add(text);
2025-11-11 10:57:35 +08:00
// 在同一个父节点下收集包含该 text 的同级节点
2025-11-07 20:47:57 +08:00
List<Transform> arrayComponents = new List<Transform>();
2025-09-05 19:46:30 +08:00
for (int j = 0; j < root.childCount; j++)
{
2025-11-11 10:57:35 +08:00
Transform sibling = root.GetChild(j);
if (sibling != null && sibling.name.Contains(text, StringComparison.Ordinal))
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
arrayComponents.Add(sibling);
2025-09-05 19:46:30 +08:00
}
}
2025-11-07 20:47:57 +08:00
CollectArrayComponent(arrayComponents, text);
2025-09-05 19:46:30 +08:00
}
2025-11-11 10:57:35 +08:00
else // 普通组件/进一步递归
2025-09-05 19:46:30 +08:00
{
CollectComponent(child);
GetBindData(child);
}
}
}
private static void CollectComponent(Transform node)
{
2025-11-11 10:57:35 +08:00
if (node == null) return;
2025-11-07 20:47:57 +08:00
string[] componentArray = SplitComponentName(node.name);
2025-11-11 10:57:35 +08:00
if (componentArray == null || componentArray.Length == 0) return;
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
foreach (var com in componentArray)
{
if (string.IsNullOrEmpty(com)) continue;
string typeName = GetVersionType(com);
if (string.IsNullOrEmpty(typeName)) continue;
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
Component component = node.GetComponent(typeName);
if (component != null)
{
string keyName = GetKeyName(com, node.name, EBindType.None);
if (_uiBindDatas.Exists(a => a.Name == keyName))
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
Debug.LogError($"Duplicate key found: {keyName}");
continue;
2025-09-05 19:46:30 +08:00
}
2025-11-11 10:57:35 +08:00
_uiBindDatas.Add(new UIBindData(keyName, component));
}
else
{
Debug.LogError($"{node.name} does not have component of type {typeName}");
2025-09-05 19:46:30 +08:00
}
}
}
private static void CollectWidget(Transform node)
{
2025-11-11 10:57:35 +08:00
if (node == null) return;
var common = UIConfiguration.UIGenerateCommonData;
if (node.name.IndexOf(common.ComCheckEndName, StringComparison.Ordinal) != -1 &&
node.name.IndexOf(common.ComCheckSplitName, StringComparison.Ordinal) != -1)
2025-09-05 19:46:30 +08:00
{
2025-11-07 20:47:57 +08:00
Debug.LogWarning($"{node.name} child component cannot contain rule definition symbols!");
2025-09-05 19:46:30 +08:00
return;
}
UIHolderObjectBase component = node.GetComponent<UIHolderObjectBase>();
2025-11-11 10:57:35 +08:00
if (component == null)
{
Debug.LogError($"{node.name} expected to be a widget but does not have UIHolderObjectBase.");
return;
}
2025-11-07 20:47:57 +08:00
2025-11-11 10:57:35 +08:00
string keyName = GetKeyName(string.Empty, node.name, EBindType.Widget);
2025-11-07 20:47:57 +08:00
if (_uiBindDatas.Exists(a => a.Name == keyName))
2025-09-05 19:46:30 +08:00
{
Debug.LogError($"Duplicate key found: {keyName}");
return;
}
2025-11-07 20:47:57 +08:00
_uiBindDatas.Add(new UIBindData(keyName, component, EBindType.Widget));
2025-09-05 19:46:30 +08:00
}
private static void CollectArrayComponent(List<Transform> arrayNode, string nodeName)
{
2025-11-11 10:57:35 +08:00
if (arrayNode == null || arrayNode.Count == 0) return;
// 从 nodeName例如 "*Item*0")取出组件描述部分(即名字中 @End 之前那部分)
2025-11-07 20:47:57 +08:00
string[] componentArray = SplitComponentName(nodeName);
2025-11-11 10:57:35 +08:00
// 对 arrayNode 做基于后缀的安全排序:提取 last segment 作为索引int.TryParse
string splitCode = UIConfiguration.UIGenerateCommonData.ArrayComSplitName;
var orderedNodes = arrayNode
.Select(n => new { Node = n, RawIndex = ExtractArrayIndex(n.name, splitCode) })
.OrderBy(x => x.RawIndex.HasValue ? x.RawIndex.Value : int.MaxValue)
.Select(x => x.Node)
.ToList();
if (componentArray == null || componentArray.Length == 0)
{
Debug.LogWarning($"CollectArrayComponent: {nodeName} has no component definitions.");
return;
}
// 准备临时 bind 列表,每个 componentArray 项对应一个 UIBindData
2025-11-07 20:47:57 +08:00
List<UIBindData> tempBindDatas = new List<UIBindData>(componentArray.Length);
2025-11-11 10:57:35 +08:00
for (int i = 0; i < componentArray.Length; i++)
{
string keyNamePreview = GetKeyName(componentArray[i], nodeName, EBindType.ListCom);
tempBindDatas.Add(new UIBindData(keyNamePreview, new List<Component>(), EBindType.ListCom));
}
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
// 遍历元素并填充
for (int index = 0; index < componentArray.Length; index++)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
string com = componentArray[index];
if (string.IsNullOrEmpty(com)) continue;
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
string typeName = GetVersionType(com);
if (string.IsNullOrEmpty(typeName)) continue;
2025-11-07 20:47:57 +08:00
2025-11-11 10:57:35 +08:00
foreach (var node in orderedNodes)
{
Component component = node.GetComponent(typeName);
if (component != null)
{
tempBindDatas[index].BindCom.Add(component);
}
else
{
Debug.LogError($"{node.name} does not have component of type {typeName}");
2025-09-05 19:46:30 +08:00
}
}
}
2025-11-11 10:57:35 +08:00
// 将结果合并到全局绑定数据
_uiBindDatas.AddRange(tempBindDatas);
}
private static int? ExtractArrayIndex(string nodeName, string splitCode)
{
if (string.IsNullOrEmpty(nodeName) || string.IsNullOrEmpty(splitCode)) return null;
int last = nodeName.LastIndexOf(splitCode, StringComparison.Ordinal);
if (last < 0) return null;
string suffix = nodeName.Substring(last + splitCode.Length);
if (int.TryParse(suffix, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int idx))
return idx;
return null;
2025-09-05 19:46:30 +08:00
}
2025-11-07 20:47:57 +08:00
private static string GetReferenceNamespace()
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
StringBuilder sb = new StringBuilder();
HashSet<string> namespaces = new HashSet<string>(StringComparer.Ordinal);
// 基础 namespace
2025-11-07 20:47:57 +08:00
namespaces.Add("UnityEngine");
2025-11-11 10:57:35 +08:00
sb.AppendLine("using UnityEngine;");
2025-11-07 20:47:57 +08:00
2025-11-11 10:57:35 +08:00
bool needCollectionsGeneric = _uiBindDatas.Any(d => d.BindType == EBindType.ListCom);
if (needCollectionsGeneric)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
namespaces.Add("System.Collections.Generic");
sb.AppendLine("using System.Collections.Generic;");
}
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
foreach (var bindData in _uiBindDatas)
{
var comp = bindData.BindCom?.FirstOrDefault();
string ns = comp?.GetType().Namespace;
if (!string.IsNullOrEmpty(ns) && !namespaces.Contains(ns))
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
namespaces.Add(ns);
sb.AppendLine($"using {ns};");
2025-09-05 19:46:30 +08:00
}
}
2025-11-11 10:57:35 +08:00
return sb.ToString();
2025-09-05 19:46:30 +08:00
}
2025-11-07 20:47:57 +08:00
private static string GetVariableText(List<UIBindData> uiBindDatas)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
if (uiBindDatas == null || uiBindDatas.Count == 0) return string.Empty;
2025-11-07 20:47:57 +08:00
StringBuilder variableTextBuilder = new StringBuilder();
2025-11-11 10:57:35 +08:00
var helper = UIGeneratorRuleHelper;
if (helper == null) throw new InvalidOperationException("UIGeneratorRuleHelper is not configured.");
2025-09-05 19:46:30 +08:00
foreach (var bindData in uiBindDatas)
{
2025-11-11 10:57:35 +08:00
if (bindData == null) continue;
2025-11-07 20:47:57 +08:00
string variableName = bindData.Name;
2025-11-11 10:57:35 +08:00
if (string.IsNullOrEmpty(variableName)) continue;
string publicName = helper.GetPublicComponentByNameRule(variableName);
2025-11-07 20:47:57 +08:00
variableTextBuilder.Append("\t\t[SerializeField]\n");
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
var firstType = bindData.BindCom?.FirstOrDefault()?.GetType();
string typeName = firstType?.Name ?? "Component";
if (bindData.BindType == EBindType.None || bindData.BindType == EBindType.Widget)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
variableTextBuilder.Append($"\t\tprivate {typeName} {variableName};\n");
variableTextBuilder.Append($"\t\tpublic {typeName} {publicName} => {variableName};\n\n");
2025-09-05 19:46:30 +08:00
}
else if (bindData.BindType == EBindType.ListCom)
{
2025-11-11 10:57:35 +08:00
int count = Math.Max(0, bindData.BindCom?.Count ?? 0);
variableTextBuilder.Append($"\t\tprivate {typeName}[] {variableName} = new {typeName}[{count}];\n");
variableTextBuilder.Append($"\t\tpublic {typeName}[] {publicName} => {variableName};\n\n");
2025-09-05 19:46:30 +08:00
}
}
2025-11-07 20:47:57 +08:00
return variableTextBuilder.ToString();
2025-09-05 19:46:30 +08:00
}
2025-11-10 16:01:53 +08:00
private static string GenerateScript(string className, string generateNameSpace)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
if (string.IsNullOrEmpty(className)) throw new ArgumentNullException(nameof(className));
if (string.IsNullOrEmpty(generateNameSpace)) throw new ArgumentNullException(nameof(generateNameSpace));
2025-09-05 19:46:30 +08:00
StringBuilder scriptBuilder = new StringBuilder();
2025-11-07 20:47:57 +08:00
scriptBuilder.Append(GetReferenceNamespace());
2025-11-11 10:57:35 +08:00
scriptBuilder.AppendLine("using AlicizaX.UI.Runtime;");
scriptBuilder.AppendLine($"namespace {generateNameSpace}");
scriptBuilder.AppendLine("{");
scriptBuilder.AppendLine("\t#Attribute#");
scriptBuilder.AppendLine($"\tpublic class {className} : UIHolderObjectBase");
scriptBuilder.AppendLine("\t{");
scriptBuilder.AppendLine("\t\tpublic const string ResTag = #Tag#;");
scriptBuilder.AppendLine("\t\t#region Generated by Script Tool\n");
2025-11-07 20:47:57 +08:00
scriptBuilder.Append(GetVariableText(_uiBindDatas));
2025-11-11 10:57:35 +08:00
scriptBuilder.AppendLine("\t\t#endregion");
scriptBuilder.AppendLine("\t}");
scriptBuilder.AppendLine("}");
2025-09-05 19:46:30 +08:00
return scriptBuilder.ToString();
}
public static void GenerateAndAttachScript(GameObject targetObject, UIScriptGenerateData scriptGenerateData)
{
2025-11-11 10:57:35 +08:00
if (targetObject == null) throw new ArgumentNullException(nameof(targetObject));
if (scriptGenerateData == null) throw new ArgumentNullException(nameof(scriptGenerateData));
2025-11-10 16:01:53 +08:00
if (!PrefabChecker.IsPrefabAsset(targetObject))
{
Debug.LogWarning("请将UI界面保存为对应的目录Prefab 在进行代码生成");
return;
}
2025-11-11 10:57:35 +08:00
var ruleHelper = UIGeneratorRuleHelper;
if (ruleHelper == null)
{
Debug.LogError("UIGeneratorRuleHelper not available, abort.");
return;
}
if (!ruleHelper.CheckCanGenerate(targetObject, scriptGenerateData))
2025-11-10 16:01:53 +08:00
{
return;
}
2025-09-10 14:26:54 +08:00
EditorPrefs.SetInt("InstanceId", targetObject.GetInstanceID());
2025-11-07 20:47:57 +08:00
_uiBindDatas.Clear();
_arrayComponents.Clear();
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
string className = ruleHelper.GetClassGenerateName(targetObject, scriptGenerateData);
if (string.IsNullOrEmpty(className))
{
Debug.LogError("Generated className is empty.");
return;
}
2025-09-05 19:46:30 +08:00
GetBindData(targetObject.transform);
2025-11-10 16:01:53 +08:00
string scriptContent = GenerateScript(className, scriptGenerateData.NameSpace);
2025-11-11 10:57:35 +08:00
string tagName = $"\"{ruleHelper.GetUIResourceSavePath(targetObject, scriptGenerateData)}\"";
2025-09-05 19:46:30 +08:00
2025-11-07 20:47:57 +08:00
string uiAttribute = $"[UIRes({className}.ResTag, EUIResLoadType.{scriptGenerateData.LoadType})]";
2025-09-05 19:46:30 +08:00
2025-11-10 16:01:53 +08:00
scriptContent = scriptContent.Replace("#Attribute#", uiAttribute);
scriptContent = scriptContent.Replace("#Tag#", tagName);
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
ruleHelper.WriteUIScriptContent(className, scriptContent, scriptGenerateData);
2025-09-05 19:46:30 +08:00
}
[DidReloadScripts]
2025-11-10 16:01:53 +08:00
public static void CheckHasAttach()
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
if (!EditorPrefs.HasKey("Generate"))
return;
2025-09-10 14:26:54 +08:00
2025-11-11 10:57:35 +08:00
_uiBindDatas.Clear();
_arrayComponents.Clear();
2025-09-10 14:26:54 +08:00
2025-11-11 10:57:35 +08:00
string className = EditorPrefs.GetString("Generate");
int instanceId = EditorPrefs.GetInt("InstanceId", -1);
2025-09-10 14:26:54 +08:00
2025-11-11 10:57:35 +08:00
if (instanceId == -1)
{
Debug.LogWarning("CheckHasAttach: InstanceId missing.");
2025-09-05 19:46:30 +08:00
EditorPrefs.DeleteKey("Generate");
2025-11-11 10:57:35 +08:00
return;
}
GameObject targetObject = EditorUtility.InstanceIDToObject(instanceId) as GameObject;
2025-09-10 14:26:54 +08:00
2025-11-11 10:57:35 +08:00
if (targetObject == null)
{
Debug.LogWarning("UI script generation attachment object missing!");
EditorPrefs.DeleteKey("Generate");
return;
2025-09-05 19:46:30 +08:00
}
2025-11-11 10:57:35 +08:00
// 重新收集 bind 数据并附加脚本
GetBindData(targetObject.transform);
AttachScriptToGameObject(targetObject, className);
Debug.Log($"Generate {className} Successfully attached to game object");
EditorPrefs.DeleteKey("Generate");
2025-09-05 19:46:30 +08:00
}
private static void AttachScriptToGameObject(GameObject targetObject, string scriptClassName)
{
2025-11-11 10:57:35 +08:00
if (targetObject == null) throw new ArgumentNullException(nameof(targetObject));
if (string.IsNullOrEmpty(scriptClassName)) throw new ArgumentNullException(nameof(scriptClassName));
2025-09-05 19:46:30 +08:00
Type scriptType = null;
2025-11-11 10:57:35 +08:00
2025-09-05 19:46:30 +08:00
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
2025-11-11 10:57:35 +08:00
// 跳过典型的编辑器专用程序集(但只在程序集名字结束或包含 ".Editor" 时跳过)
var asmName = assembly.GetName().Name ?? string.Empty;
if (asmName.EndsWith(".Editor", StringComparison.OrdinalIgnoreCase) ||
asmName.Equals("UnityEditor", StringComparison.OrdinalIgnoreCase))
{
continue;
}
Type[] types;
try
{
types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
types = e.Types.Where(t => t != null).ToArray();
}
2025-09-05 19:46:30 +08:00
foreach (var type in types)
{
2025-11-11 10:57:35 +08:00
if (type == null) continue;
if (!type.IsClass || type.IsAbstract) continue;
if (type.Name.Equals(scriptClassName, StringComparison.Ordinal) ||
type.Name.Contains(scriptClassName, StringComparison.Ordinal))
2025-09-05 19:46:30 +08:00
{
scriptType = type;
2025-11-11 10:57:35 +08:00
break;
2025-09-05 19:46:30 +08:00
}
}
2025-11-11 10:57:35 +08:00
if (scriptType != null) break;
2025-09-05 19:46:30 +08:00
}
2025-11-11 10:57:35 +08:00
if (scriptType == null)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
Debug.LogError($"Could not find the class: {scriptClassName}");
return;
}
2025-09-05 19:46:30 +08:00
2025-11-11 10:57:35 +08:00
Component component = targetObject.GetOrAddComponent(scriptType);
FieldInfo[] fields = scriptType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (string.IsNullOrEmpty(field.Name)) continue;
var componentInObjects = _uiBindDatas.Find(data => data.Name == field.Name)?.BindCom;
if (componentInObjects == null)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
Debug.LogError($"Field {field.Name} did not find matching component binding");
continue;
}
if (field.FieldType.IsArray)
{
Type elementType = field.FieldType.GetElementType();
if (elementType == null)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
Debug.LogError($"Field {field.Name} has unknown element type.");
continue;
}
Array array = Array.CreateInstance(elementType, componentInObjects.Count);
for (int i = 0; i < componentInObjects.Count; i++)
{
Component comp = componentInObjects[i];
if (comp == null) continue;
if (elementType.IsInstanceOfType(comp))
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
array.SetValue(comp, i);
2025-09-05 19:46:30 +08:00
}
else
{
2025-11-11 10:57:35 +08:00
Debug.LogError($"Element {i} type mismatch for field {field.Name}, expected {elementType.Name}, actual {comp.GetType().Name}");
2025-09-05 19:46:30 +08:00
}
}
2025-11-11 10:57:35 +08:00
field.SetValue(component, array);
}
else
{
if (componentInObjects.Count > 0)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
var first = componentInObjects[0];
if (first == null) continue;
if (field.FieldType.IsInstanceOfType(first))
{
field.SetValue(component, first);
}
else
{
Debug.LogError($"Field {field.Name} type mismatch, cannot assign value. Field expects {field.FieldType.Name}, actual {first.GetType().Name}");
}
2025-09-05 19:46:30 +08:00
}
}
}
}
2025-11-10 16:01:53 +08:00
public static class PrefabChecker
{
public static bool IsEditingPrefabAsset(GameObject go)
{
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage == null)
return false;
return prefabStage.IsPartOfPrefabContents(go);
}
public static bool IsPrefabAsset(GameObject go)
{
2025-11-11 10:57:35 +08:00
if (go == null) return false;
2025-11-10 16:01:53 +08:00
var assetType = PrefabUtility.GetPrefabAssetType(go);
if (assetType == PrefabAssetType.Regular ||
assetType == PrefabAssetType.Variant ||
assetType == PrefabAssetType.Model)
return true;
return IsEditingPrefabAsset(go);
}
}
2025-09-05 19:46:30 +08:00
}
}