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

849 lines
32 KiB
C#
Raw Normal View History

2025-09-05 19:46:30 +08:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using AlicizaX.UI.Runtime;
using UnityEditor;
using UnityEditor.Callbacks;
2025-11-10 16:01:53 +08:00
using UnityEditor.SceneManagement;
2025-11-13 11:16:31 +08:00
using UnityEngine;
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,
2025-11-13 11:16:31 +08:00
ListCom
2025-11-11 10:57:35 +08:00
}
2025-09-05 19:46:30 +08:00
[Serializable]
2025-11-13 11:16:31 +08:00
public class UIBindData
2025-09-05 19:46:30 +08:00
{
2026-03-16 18:33:06 +08:00
public UIBindData(string name, List<GameObject> objs, Type componentType = null, EBindType bindType = EBindType.None)
{
Name = name;
Objs = objs ?? new List<GameObject>();
BindType = bindType;
ComponentType = componentType;
}
public UIBindData(string name, GameObject obj, Type componentType = null, EBindType bindType = EBindType.None)
: this(name, new List<GameObject> { obj }, componentType, bindType)
{
}
2025-11-13 11:16:31 +08:00
public string Name { get; }
public List<GameObject> Objs { get; set; }
2026-03-16 18:33:06 +08:00
public EBindType BindType { get; }
2025-09-05 19:46:30 +08:00
2026-03-16 18:33:06 +08:00
public Type ComponentType { get; private set; }
2026-03-16 18:33:06 +08:00
public bool IsGameObject => ComponentType == typeof(GameObject);
2025-12-01 16:45:42 +08:00
2026-03-16 18:33:06 +08:00
public string TypeName => ComponentType?.FullName ?? string.Empty;
2026-03-16 18:33:06 +08:00
public Type GetFirstOrDefaultType() => ComponentType;
2025-09-05 19:46:30 +08:00
2026-03-16 18:33:06 +08:00
public void SetComponentType(Type componentType)
2025-09-05 19:46:30 +08:00
{
2026-03-16 18:33:06 +08:00
ComponentType = componentType;
2025-09-05 19:46:30 +08:00
}
}
2025-12-01 16:45:42 +08:00
public static class UIScriptGeneratorHelper
2025-09-05 19:46:30 +08:00
{
2026-03-16 18:33:06 +08:00
private const string GenerateTypeNameKey = "AlicizaX.UI.Generate.TypeName";
private const string GenerateInstanceIdKey = "AlicizaX.UI.Generate.InstanceId";
private const string GenerateAssetPathKey = "AlicizaX.UI.Generate.AssetPath";
2025-09-05 19:46:30 +08:00
private static UIGenerateConfiguration _uiGenerateConfiguration;
private static IUIIdentifierFormatter _identifierFormatter;
private static IUIResourcePathResolver _resourcePathResolver;
private static IUIScriptCodeEmitter _scriptCodeEmitter;
private static IUIScriptFileWriter _scriptFileWriter;
2025-11-13 11:16:31 +08:00
private static readonly List<UIBindData> _uiBindDatas = new List<UIBindData>();
private static readonly HashSet<string> _arrayComponents = new HashSet<string>(StringComparer.Ordinal);
2026-03-16 18:33:06 +08:00
private static readonly Dictionary<string, Type> _componentTypeCache = new Dictionary<string, Type>(StringComparer.Ordinal);
2025-11-07 20:47:57 +08:00
private static UIGenerateConfiguration UIConfiguration =>
_uiGenerateConfiguration ??= UIGenerateConfiguration.Instance;
private static IUIIdentifierFormatter IdentifierFormatter =>
ResolveConfiguredService(
ref _identifierFormatter,
UIConfiguration.UIIdentifierFormatterTypeName,
typeof(DefaultUIIdentifierFormatter),
nameof(IUIIdentifierFormatter));
private static IUIResourcePathResolver ResourcePathResolver =>
ResolveConfiguredService(
ref _resourcePathResolver,
UIConfiguration.UIResourcePathResolverTypeName,
typeof(DefaultUIResourcePathResolver),
nameof(IUIResourcePathResolver));
private static IUIScriptCodeEmitter ScriptCodeEmitter =>
ResolveConfiguredService(
ref _scriptCodeEmitter,
UIConfiguration.UIScriptCodeEmitterTypeName,
typeof(DefaultUIScriptCodeEmitter),
nameof(IUIScriptCodeEmitter));
private static IUIScriptFileWriter ScriptFileWriter =>
ResolveConfiguredService(
ref _scriptFileWriter,
UIConfiguration.UIScriptFileWriterTypeName,
typeof(DefaultUIScriptFileWriter),
nameof(IUIScriptFileWriter));
private static T ResolveConfiguredService<T>(ref T cachedService, string configuredTypeName, Type defaultType, string serviceName)
where T : class
2025-12-01 16:45:42 +08:00
{
var resolvedTypeName = string.IsNullOrWhiteSpace(configuredTypeName) ? defaultType.FullName : configuredTypeName;
if (cachedService != null && cachedService.GetType().FullName == resolvedTypeName)
2025-12-01 16:45:42 +08:00
{
return cachedService;
}
2026-03-16 18:33:06 +08:00
var configuredType = AlicizaX.Utility.Assembly.GetType(resolvedTypeName);
if (configuredType == null || !typeof(T).IsAssignableFrom(configuredType))
{
if (!string.Equals(resolvedTypeName, defaultType.FullName, StringComparison.Ordinal))
2025-12-01 16:45:42 +08:00
{
Debug.LogError(
$"UIScriptGeneratorHelper: Could not load {serviceName} type '{resolvedTypeName}'. Falling back to {defaultType.FullName}.");
2025-12-01 16:45:42 +08:00
}
configuredType = defaultType;
2025-12-01 16:45:42 +08:00
}
2025-11-11 10:57:35 +08:00
cachedService = Activator.CreateInstance(configuredType, true) as T;
if (cachedService != null)
2025-11-07 20:47:57 +08:00
{
return cachedService;
2025-11-07 20:47:57 +08:00
}
if (configuredType != defaultType)
2025-09-05 19:46:30 +08:00
{
Debug.LogError(
$"UIScriptGeneratorHelper: Failed to instantiate {resolvedTypeName} as {serviceName}. Falling back to {defaultType.FullName}.");
cachedService = Activator.CreateInstance(defaultType, true) as T;
2025-11-13 11:16:31 +08:00
}
2025-09-05 19:46:30 +08:00
if (cachedService == null)
2025-11-13 11:16:31 +08:00
{
Debug.LogError($"UIScriptGeneratorHelper: Failed to instantiate fallback {defaultType.FullName} as {serviceName}.");
2025-09-05 19:46:30 +08:00
}
2025-11-13 11:16:31 +08:00
return cachedService;
}
private static bool EnsureGenerationStrategyReady()
{
return IdentifierFormatter != null &&
ResourcePathResolver != null &&
ScriptCodeEmitter != null &&
ScriptFileWriter != null;
2025-09-05 19:46:30 +08:00
}
2026-03-16 18:33:06 +08:00
private static Type ResolveUIElementComponentType(string uiName)
2025-09-05 19:46:30 +08:00
{
2026-03-16 18:33:06 +08:00
if (string.IsNullOrEmpty(uiName))
{
return null;
}
var componentTypeName = UIConfiguration.UIElementRegexConfigs
2025-11-13 11:16:31 +08:00
?.Where(pair => !string.IsNullOrEmpty(pair?.uiElementRegex))
.FirstOrDefault(pair => uiName.StartsWith(pair.uiElementRegex, StringComparison.Ordinal))
2026-03-16 18:33:06 +08:00
?.componentType;
if (string.IsNullOrWhiteSpace(componentTypeName))
{
return null;
}
if (_componentTypeCache.TryGetValue(componentTypeName, out var componentType))
{
return componentType;
}
componentType = ResolveConfiguredComponentType(componentTypeName);
2026-03-16 18:33:06 +08:00
if (componentType == null)
{
Debug.LogError($"UIScriptGeneratorHelper: Could not resolve component type '{componentTypeName}' for '{uiName}'.");
return null;
}
_componentTypeCache[componentTypeName] = componentType;
2026-03-16 18:33:06 +08:00
return componentType;
2025-09-05 19:46:30 +08:00
}
private static Type ResolveConfiguredComponentType(string componentTypeName)
{
if (string.IsNullOrWhiteSpace(componentTypeName))
{
return null;
}
if (componentTypeName == nameof(GameObject))
{
return typeof(GameObject);
}
Type componentType = AlicizaX.Utility.Assembly.GetType(componentTypeName);
if (componentType != null && typeof(Component).IsAssignableFrom(componentType))
{
return componentType;
}
return AlicizaX.Utility.Assembly.GetTypes()
.Where(type => type != null && !type.IsAbstract && !type.IsInterface)
.Where(type => typeof(Component).IsAssignableFrom(type))
.Where(type => string.Equals(type.FullName, componentTypeName, StringComparison.Ordinal)
|| string.Equals(type.Name, componentTypeName, StringComparison.Ordinal))
.OrderBy(type => string.Equals(type.FullName, componentTypeName, StringComparison.Ordinal) ? 0 : 1)
.ThenBy(type => string.Equals(type.Namespace, "UnityEngine.UI", StringComparison.Ordinal) ? 0 : 1)
.ThenBy(type => type.FullName, StringComparer.Ordinal)
.FirstOrDefault();
}
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;
2025-11-13 11:16:31 +08:00
var endIndex = name.IndexOf(common.ComCheckEndName, StringComparison.Ordinal);
2025-11-11 10:57:35 +08:00
if (endIndex <= 0) return null;
2025-09-05 19:46:30 +08:00
2025-11-13 11:16:31 +08:00
var comStr = name.Substring(0, endIndex);
var split = common.ComCheckSplitName ?? "#";
2025-09-05 19:46:30 +08:00
2025-11-13 11:16:31 +08:00
return comStr.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);
2025-09-05 19:46:30 +08:00
}
2025-11-13 11:16:31 +08:00
private static void CollectBindData(Transform root)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
if (root == null) return;
2025-11-13 11:16:31 +08:00
foreach (Transform child in root.Cast<Transform>().Where(child => child != null))
2025-09-05 19:46:30 +08:00
{
2025-11-13 11:16:31 +08:00
if (ShouldSkipChild(child)) continue;
var hasWidget = child.GetComponent<UIHolderObjectBase>() != null;
var isArrayComponent = IsArrayComponent(child.name);
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-13 11:16:31 +08:00
ProcessArrayComponent(child, root);
2025-09-05 19:46:30 +08:00
}
2025-11-13 11:16:31 +08:00
else
2025-09-05 19:46:30 +08:00
{
CollectComponent(child);
2025-11-13 11:16:31 +08:00
CollectBindData(child);
2025-09-05 19:46:30 +08:00
}
}
}
2025-11-13 11:16:31 +08:00
private static bool ShouldSkipChild(Transform child)
{
var keywords = UIConfiguration.UIGenerateCommonData.ExcludeKeywords;
return keywords?.Any(k =>
!string.IsNullOrEmpty(k) &&
child.name.IndexOf(k, StringComparison.OrdinalIgnoreCase) >= 0) == true;
}
private static bool IsArrayComponent(string componentName)
{
var splitName = UIConfiguration.UIGenerateCommonData.ArrayComSplitName;
return !string.IsNullOrEmpty(splitName) &&
componentName.StartsWith(splitName, StringComparison.Ordinal);
}
private static void ProcessArrayComponent(Transform child, Transform root)
{
var splitCode = UIConfiguration.UIGenerateCommonData.ArrayComSplitName;
2026-03-16 18:33:06 +08:00
if (!TryGetArrayComponentGroupName(child.name, splitCode, out var groupName))
{
return;
}
2025-11-13 11:16:31 +08:00
2026-03-16 18:33:06 +08:00
var groupKey = $"{root.GetInstanceID()}::{groupName}";
if (!_arrayComponents.Add(groupKey))
{
return;
}
2025-11-13 11:16:31 +08:00
var arrayComponents = root.Cast<Transform>()
2026-03-16 18:33:06 +08:00
.Where(sibling => IsArrayGroupMember(sibling.name, splitCode, groupName))
2025-11-13 11:16:31 +08:00
.ToList();
2026-03-16 18:33:06 +08:00
CollectArrayComponent(arrayComponents, groupName);
2025-11-13 11:16:31 +08:00
}
2025-09-05 19:46:30 +08:00
private static void CollectComponent(Transform node)
{
2025-11-11 10:57:35 +08:00
if (node == null) return;
2025-11-13 11:16:31 +08:00
var 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-13 11:16:31 +08:00
foreach (var com in componentArray.Where(com => !string.IsNullOrEmpty(com)))
2025-11-11 10:57:35 +08:00
{
2026-03-16 18:33:06 +08:00
var componentType = ResolveUIElementComponentType(com);
if (componentType == null)
{
continue;
}
if (componentType != typeof(GameObject) && ResolveAssignableComponent(node.gameObject, componentType) == null)
2025-11-11 10:57:35 +08:00
{
2026-03-16 18:33:06 +08:00
Debug.LogError($"{node.name} does not have component of type {componentType.FullName}");
continue;
2025-11-11 10:57:35 +08:00
}
2025-11-13 11:16:31 +08:00
var keyName = GetPrivateComponentName(com, node.name, EBindType.None);
2025-11-13 11:16:31 +08:00
if (_uiBindDatas.Exists(data => data.Name == keyName))
2025-11-11 10:57:35 +08:00
{
2025-11-13 11:16:31 +08:00
Debug.LogError($"Duplicate key found: {keyName}");
continue;
2025-09-05 19:46:30 +08:00
}
2025-11-13 11:16:31 +08:00
2026-03-16 18:33:06 +08:00
_uiBindDatas.Add(new UIBindData(keyName, node.gameObject, componentType));
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;
2025-11-13 11:16:31 +08:00
if (node.name.Contains(common.ComCheckEndName, StringComparison.Ordinal) &&
node.name.Contains(common.ComCheckSplitName, StringComparison.Ordinal))
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;
}
2025-11-13 11:16:31 +08:00
var 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
var keyName = GetPrivateComponentName(string.Empty, node.name, EBindType.Widget);
2025-11-13 11:16:31 +08:00
if (_uiBindDatas.Exists(data => data.Name == keyName))
2025-09-05 19:46:30 +08:00
{
Debug.LogError($"Duplicate key found: {keyName}");
return;
}
2026-03-16 18:33:06 +08:00
_uiBindDatas.Add(new UIBindData(keyName, component.gameObject, component.GetType(), EBindType.Widget));
2025-09-05 19:46:30 +08:00
}
private static void CollectArrayComponent(List<Transform> arrayNode, string nodeName)
{
2025-11-13 11:16:31 +08:00
if (arrayNode == null || !arrayNode.Any()) return;
2025-11-11 10:57:35 +08:00
2025-11-13 11:16:31 +08:00
var componentArray = SplitComponentName(nodeName);
2025-11-11 10:57:35 +08:00
if (componentArray == null || componentArray.Length == 0)
{
Debug.LogWarning($"CollectArrayComponent: {nodeName} has no component definitions.");
return;
}
2025-11-13 11:16:31 +08:00
var orderedNodes = OrderArrayNodes(arrayNode);
var tempBindDatas = CreateTempBindDatas(componentArray, nodeName);
PopulateArrayComponents(componentArray, orderedNodes, tempBindDatas);
_uiBindDatas.AddRange(tempBindDatas);
}
private static List<Transform> OrderArrayNodes(List<Transform> arrayNode)
{
var splitCode = UIConfiguration.UIGenerateCommonData.ArrayComSplitName;
return arrayNode
.Select(node => new { Node = node, Index = ExtractArrayIndex(node.name, splitCode) })
.OrderBy(x => x.Index ?? int.MaxValue)
.Select(x => x.Node)
.ToList();
}
private static List<UIBindData> CreateTempBindDatas(string[] componentArray, string nodeName)
{
2026-03-16 18:33:06 +08:00
return componentArray.Select(com =>
2025-11-11 10:57:35 +08:00
{
var keyName = GetPrivateComponentName(com, nodeName, EBindType.ListCom);
2026-03-16 18:33:06 +08:00
return new UIBindData(keyName, new List<GameObject>(), null, EBindType.ListCom);
2025-11-13 11:16:31 +08:00
}).ToList();
}
2025-09-05 19:46:30 +08:00
2025-11-13 11:16:31 +08:00
private static void PopulateArrayComponents(string[] componentArray, List<Transform> orderedNodes, List<UIBindData> tempBindDatas)
{
for (var index = 0; index < componentArray.Length; index++)
2025-09-05 19:46:30 +08:00
{
2025-11-13 11:16:31 +08:00
var com = componentArray[index];
2025-11-11 10:57:35 +08:00
if (string.IsNullOrEmpty(com)) continue;
2025-09-05 19:46:30 +08:00
2026-03-16 18:33:06 +08:00
var componentType = ResolveUIElementComponentType(com);
if (componentType == null) continue;
tempBindDatas[index].SetComponentType(componentType);
2025-11-11 10:57:35 +08:00
foreach (var node in orderedNodes)
{
2026-03-16 18:33:06 +08:00
var isGameObject = componentType == typeof(GameObject);
var component = isGameObject ? null : ResolveAssignableComponent(node.gameObject, componentType);
if (component != null || isGameObject)
2025-11-11 10:57:35 +08:00
{
tempBindDatas[index].Objs.Add(node.gameObject);
2025-11-11 10:57:35 +08:00
}
else
{
2026-03-16 18:33:06 +08:00
Debug.LogError($"{node.name} does not have component of type {componentType.FullName}");
2025-09-05 19:46:30 +08:00
}
}
}
2025-11-11 10:57:35 +08:00
}
2026-03-16 18:33:06 +08:00
private static bool TryGetArrayComponentGroupName(string nodeName, string splitCode, out string groupName)
{
groupName = null;
if (string.IsNullOrEmpty(nodeName) || string.IsNullOrEmpty(splitCode))
{
return false;
}
var firstIndex = nodeName.IndexOf(splitCode, StringComparison.Ordinal);
var lastIndex = nodeName.LastIndexOf(splitCode, StringComparison.Ordinal);
if (firstIndex < 0 || lastIndex <= firstIndex)
{
return false;
}
groupName = nodeName.Substring(firstIndex + splitCode.Length, lastIndex - (firstIndex + splitCode.Length));
return !string.IsNullOrEmpty(groupName);
}
private static bool IsArrayGroupMember(string nodeName, string splitCode, string groupName)
{
return TryGetArrayComponentGroupName(nodeName, splitCode, out var candidateGroupName) &&
candidateGroupName.Equals(groupName, StringComparison.Ordinal) &&
ExtractArrayIndex(nodeName, splitCode).HasValue;
}
2025-11-11 10:57:35 +08:00
private static int? ExtractArrayIndex(string nodeName, string splitCode)
{
if (string.IsNullOrEmpty(nodeName) || string.IsNullOrEmpty(splitCode)) return null;
2025-11-13 11:16:31 +08:00
var lastIndex = nodeName.LastIndexOf(splitCode, StringComparison.Ordinal);
if (lastIndex < 0) return null;
2025-09-05 19:46:30 +08:00
2025-11-13 11:16:31 +08:00
var suffix = nodeName.Substring(lastIndex + splitCode.Length);
return int.TryParse(suffix, out var idx) ? idx : (int?)null;
2025-09-05 19:46:30 +08:00
}
2025-11-13 11:16:31 +08:00
public static void GenerateUIBindScript(GameObject targetObject, UIScriptGenerateData scriptGenerateData)
2025-09-05 19:46:30 +08:00
{
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))
{
2026-03-16 18:33:06 +08:00
Debug.LogWarning("Please save the UI as a prefab asset before generating bindings.");
2025-11-10 16:01:53 +08:00
return;
}
if (!EnsureGenerationStrategyReady())
2025-11-10 16:01:53 +08:00
{
return;
}
2025-11-13 11:16:31 +08:00
InitializeGenerationContext(targetObject);
2026-03-16 18:33:06 +08:00
CollectBindData(targetObject.transform);
var generationContext = new UIGenerationContext(targetObject, scriptGenerateData, _uiBindDatas)
{
AssetPath = UIGenerateQuick.GetPrefabAssetPath(targetObject),
ClassName = GetClassGenerateName(targetObject, scriptGenerateData)
2026-03-16 18:33:06 +08:00
};
2025-09-05 19:46:30 +08:00
if (!CheckCanGenerate(generationContext))
2025-11-11 10:57:35 +08:00
{
2026-03-16 18:33:06 +08:00
CleanupContext();
2025-11-11 10:57:35 +08:00
return;
}
2025-09-05 19:46:30 +08:00
2026-03-16 18:33:06 +08:00
var validationResult = ValidateGeneration(generationContext);
if (!validationResult.IsValid)
{
Debug.LogError(validationResult.Message);
CleanupContext();
return;
}
GenerateScript(generationContext);
2025-09-05 19:46:30 +08:00
}
2025-11-13 11:16:31 +08:00
private static void InitializeGenerationContext(GameObject targetObject)
2025-09-05 19:46:30 +08:00
{
2026-03-16 18:33:06 +08:00
EditorPrefs.SetInt(GenerateInstanceIdKey, targetObject.GetInstanceID());
var assetPath = UIGenerateQuick.GetPrefabAssetPath(targetObject);
if (!string.IsNullOrEmpty(assetPath))
{
EditorPrefs.SetString(GenerateAssetPathKey, assetPath);
}
2025-11-11 10:57:35 +08:00
_uiBindDatas.Clear();
_arrayComponents.Clear();
_componentTypeCache.Clear();
2025-11-13 11:16:31 +08:00
}
2025-09-10 14:26:54 +08:00
2026-03-16 18:33:06 +08:00
private static UIGenerationValidationResult ValidateGeneration(UIGenerationContext context)
{
if (context.TargetObject == null)
{
return UIGenerationValidationResult.Fail("UI generation target is null.");
}
if (context.ScriptGenerateData == null)
{
return UIGenerationValidationResult.Fail("UI generation config is null.");
}
if (string.IsNullOrWhiteSpace(context.ClassName))
{
return UIGenerationValidationResult.Fail("Generated class name is empty.");
}
if (!File.Exists(UIGlobalPath.TemplatePath))
{
return UIGenerationValidationResult.Fail($"UI template file not found: {UIGlobalPath.TemplatePath}");
}
return UIGenerationValidationResult.Success();
}
private static void GenerateScript(UIGenerationContext context)
2025-11-13 11:16:31 +08:00
{
var templateText = File.ReadAllText(UIGlobalPath.TemplatePath);
var processedText = ProcessTemplateText(context, templateText);
2026-03-16 18:33:06 +08:00
EditorPrefs.SetString(GenerateTypeNameKey, context.FullTypeName);
WriteScriptContent(context, processedText);
2025-11-13 11:16:31 +08:00
}
2025-11-12 17:48:41 +08:00
private static string ProcessTemplateText(UIGenerationContext context, string templateText)
2025-11-13 11:16:31 +08:00
{
return templateText
.Replace("#ReferenceNameSpace#", GetReferenceNamespace(context))
2026-03-16 18:33:06 +08:00
.Replace("#ClassNameSpace#", context.ScriptGenerateData.NameSpace)
.Replace("#ClassName#", context.ClassName)
.Replace("#TagName#", GetResourceSavePath(context))
2026-03-16 18:33:06 +08:00
.Replace("#LoadType#", context.ScriptGenerateData.LoadType.ToString())
.Replace("#Variable#", GetVariableContent(context));
2026-03-16 18:33:06 +08:00
}
private static string GetClassGenerateName(GameObject targetObject, UIScriptGenerateData scriptGenerateData)
2026-03-16 18:33:06 +08:00
{
return IdentifierFormatter.GetClassName(targetObject);
}
2026-03-16 18:33:06 +08:00
private static bool CheckCanGenerate(UIGenerationContext context)
{
return ResourcePathResolver.CanGenerate(context.TargetObject, context.ScriptGenerateData);
2026-03-16 18:33:06 +08:00
}
private static string GetPrivateComponentName(string regexName, string componentName, EBindType bindType)
2026-03-16 18:33:06 +08:00
{
return IdentifierFormatter.GetPrivateComponentName(regexName, componentName, bindType);
}
private static string GetPublicComponentName(string variableName)
{
return IdentifierFormatter.GetPublicComponentName(variableName);
}
private static string GetResourceSavePath(UIGenerationContext context)
{
return ResourcePathResolver.GetResourcePath(context.TargetObject, context.ScriptGenerateData);
}
private static string GetReferenceNamespace(UIGenerationContext context)
{
return ScriptCodeEmitter.GetReferenceNamespaces(_uiBindDatas);
}
private static string GetVariableContent(UIGenerationContext context)
{
return ScriptCodeEmitter.GetVariableContent(_uiBindDatas, GetPublicComponentName);
}
2026-03-16 18:33:06 +08:00
private static void WriteScriptContent(UIGenerationContext context, string scriptContent)
{
ScriptFileWriter.Write(context.TargetObject, context.ClassName, scriptContent, context.ScriptGenerateData);
2025-11-13 11:16:31 +08:00
}
[DidReloadScripts]
public static void BindUIScript()
{
2026-03-16 18:33:06 +08:00
if (!EditorPrefs.HasKey(GenerateTypeNameKey)) return;
2025-11-11 10:57:35 +08:00
2026-03-16 18:33:06 +08:00
var scriptTypeName = EditorPrefs.GetString(GenerateTypeNameKey);
var targetObject = ResolveGenerationTarget();
2025-09-10 14:26:54 +08:00
2025-11-11 10:57:35 +08:00
if (targetObject == null)
{
2026-03-16 18:33:06 +08:00
Debug.LogWarning("UI script generation attachment object missing.");
CleanupContext();
2025-11-11 10:57:35 +08:00
return;
2025-09-05 19:46:30 +08:00
}
2025-11-11 10:57:35 +08:00
if (!EnsureGenerationStrategyReady())
{
CleanupContext();
return;
}
2025-11-13 11:16:31 +08:00
_uiBindDatas.Clear();
_arrayComponents.Clear();
2025-11-12 17:48:41 +08:00
2026-03-16 18:33:06 +08:00
var bindSucceeded = false;
2025-11-13 11:16:31 +08:00
CollectBindData(targetObject.transform);
2025-12-01 16:45:42 +08:00
try
{
2026-03-16 18:33:06 +08:00
bindSucceeded = BindScriptPropertyField(targetObject, scriptTypeName);
2025-12-01 16:45:42 +08:00
}
2026-03-16 18:33:06 +08:00
catch (Exception exception)
2025-12-01 16:45:42 +08:00
{
2026-03-16 18:33:06 +08:00
Debug.LogException(exception);
2025-12-01 16:45:42 +08:00
}
finally
{
CleanupContext();
}
2026-03-16 18:33:06 +08:00
if (!bindSucceeded)
{
return;
}
2025-12-01 16:45:42 +08:00
EditorUtility.SetDirty(targetObject);
2026-03-16 18:33:06 +08:00
Debug.Log($"Generate {scriptTypeName} successfully attached to game object.");
}
private static GameObject ResolveGenerationTarget()
{
var instanceId = EditorPrefs.GetInt(GenerateInstanceIdKey, -1);
var instanceTarget = EditorUtility.InstanceIDToObject(instanceId) as GameObject;
if (instanceTarget != null)
{
return instanceTarget;
}
var assetPath = EditorPrefs.GetString(GenerateAssetPathKey, string.Empty);
return string.IsNullOrEmpty(assetPath) ? null : AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
2025-11-13 11:16:31 +08:00
}
2025-11-12 17:48:41 +08:00
2025-11-13 11:16:31 +08:00
private static void CleanupContext()
{
2026-03-16 18:33:06 +08:00
EditorPrefs.DeleteKey(GenerateTypeNameKey);
EditorPrefs.DeleteKey(GenerateInstanceIdKey);
EditorPrefs.DeleteKey(GenerateAssetPathKey);
2025-11-13 11:16:31 +08:00
_uiBindDatas.Clear();
_arrayComponents.Clear();
_componentTypeCache.Clear();
2025-09-05 19:46:30 +08:00
}
2026-03-16 18:33:06 +08:00
private static bool BindScriptPropertyField(GameObject targetObject, string scriptTypeName)
2025-09-05 19:46:30 +08:00
{
2025-11-11 10:57:35 +08:00
if (targetObject == null) throw new ArgumentNullException(nameof(targetObject));
2026-03-16 18:33:06 +08:00
if (string.IsNullOrEmpty(scriptTypeName)) throw new ArgumentNullException(nameof(scriptTypeName));
2025-11-11 10:57:35 +08:00
2026-03-16 18:33:06 +08:00
var scriptType = FindScriptType(scriptTypeName);
2025-11-13 11:16:31 +08:00
if (scriptType == null)
{
2026-03-16 18:33:06 +08:00
Debug.LogError($"Could not find the class: {scriptTypeName}");
return false;
2025-11-13 11:16:31 +08:00
}
var targetHolder = targetObject.GetOrAddComponent(scriptType);
2026-03-16 18:33:06 +08:00
return BindFieldsToComponents(targetHolder, scriptType);
2025-11-13 11:16:31 +08:00
}
2026-03-16 18:33:06 +08:00
private static Type FindScriptType(string scriptTypeName)
2025-11-13 11:16:31 +08:00
{
2026-03-16 18:33:06 +08:00
var resolvedType = AlicizaX.Utility.Assembly.GetType(scriptTypeName);
if (resolvedType != null)
{
return resolvedType;
}
2025-11-13 11:16:31 +08:00
return AppDomain.CurrentDomain.GetAssemblies()
2026-03-16 18:33:06 +08:00
.Where(assembly => !assembly.GetName().Name.EndsWith(".Editor", StringComparison.Ordinal) &&
!assembly.GetName().Name.Equals("UnityEditor", StringComparison.Ordinal))
.SelectMany(assembly => assembly.GetTypes())
2025-11-13 11:16:31 +08:00
.FirstOrDefault(type => type.IsClass && !type.IsAbstract &&
2026-03-16 18:33:06 +08:00
type.FullName.Equals(scriptTypeName, StringComparison.Ordinal));
2025-11-13 11:16:31 +08:00
}
2026-03-16 18:33:06 +08:00
private static bool BindFieldsToComponents(Component targetHolder, Type scriptType)
2025-11-13 11:16:31 +08:00
{
2026-03-16 18:33:06 +08:00
var fields = scriptType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(field =>
2025-12-01 16:45:42 +08:00
field.GetCustomAttributes(typeof(SerializeField), false).Length > 0
);
2025-11-11 10:57:35 +08:00
2026-03-16 18:33:06 +08:00
var isSuccessful = true;
2025-11-13 11:16:31 +08:00
foreach (var field in fields.Where(field => !string.IsNullOrEmpty(field.Name)))
2025-09-05 19:46:30 +08:00
{
var bindData = _uiBindDatas.Find(data => data.Name == field.Name);
2026-03-16 18:33:06 +08:00
if (bindData == null)
2025-11-11 10:57:35 +08:00
{
2026-03-16 18:33:06 +08:00
Debug.LogError($"Field {field.Name} did not find matching component binding.");
isSuccessful = false;
2025-11-11 10:57:35 +08:00
continue;
}
2026-03-16 18:33:06 +08:00
if (!SetFieldValue(field, bindData, targetHolder))
{
isSuccessful = false;
}
2025-11-13 11:16:31 +08:00
}
2026-03-16 18:33:06 +08:00
return isSuccessful;
2025-11-13 11:16:31 +08:00
}
2025-11-11 10:57:35 +08:00
2026-03-16 18:33:06 +08:00
private static bool SetFieldValue(FieldInfo field, UIBindData bindData, Component targetComponent)
2025-11-13 11:16:31 +08:00
{
if (field.FieldType.IsArray)
{
2026-03-16 18:33:06 +08:00
return SetArrayFieldValue(field, bindData, targetComponent);
2025-09-05 19:46:30 +08:00
}
2026-03-16 18:33:06 +08:00
return SetSingleFieldValue(field, bindData, targetComponent);
2025-11-13 11:16:31 +08:00
}
2025-09-05 19:46:30 +08:00
2026-03-16 18:33:06 +08:00
private static bool SetArrayFieldValue(FieldInfo field, UIBindData bindData, Component targetComponent)
2025-11-13 11:16:31 +08:00
{
var elementType = field.FieldType.GetElementType();
if (elementType == null)
2025-09-05 19:46:30 +08:00
{
2025-11-13 11:16:31 +08:00
Debug.LogError($"Field {field.Name} has unknown element type.");
2026-03-16 18:33:06 +08:00
return false;
2025-11-11 10:57:35 +08:00
}
2025-09-05 19:46:30 +08:00
2026-03-16 18:33:06 +08:00
var components = bindData.Objs;
2025-11-13 11:16:31 +08:00
var array = Array.CreateInstance(elementType, components.Count);
2026-03-16 18:33:06 +08:00
var isSuccessful = true;
2025-11-13 11:16:31 +08:00
for (var i = 0; i < components.Count; i++)
2025-11-11 10:57:35 +08:00
{
2025-11-13 11:16:31 +08:00
if (components[i] == null) continue;
2025-11-11 10:57:35 +08:00
2026-03-16 18:33:06 +08:00
var componentObject = ResolveBoundObject(components[i], bindData.ComponentType);
2026-03-16 18:33:06 +08:00
if (componentObject != null && elementType.IsInstanceOfType(componentObject))
2025-11-11 10:57:35 +08:00
{
2026-03-16 18:33:06 +08:00
array.SetValue(componentObject, i);
2025-11-11 10:57:35 +08:00
}
else
{
2025-11-13 11:16:31 +08:00
Debug.LogError($"Element {i} type mismatch for field {field.Name}");
2026-03-16 18:33:06 +08:00
isSuccessful = false;
2025-09-05 19:46:30 +08:00
}
}
2025-11-13 11:16:31 +08:00
field.SetValue(targetComponent, array);
2026-03-16 18:33:06 +08:00
return isSuccessful;
2025-11-13 11:16:31 +08:00
}
2026-03-16 18:33:06 +08:00
private static bool SetSingleFieldValue(FieldInfo field, UIBindData bindData, Component targetComponent)
2025-11-13 11:16:31 +08:00
{
2026-03-16 18:33:06 +08:00
if (bindData.Objs.Count == 0)
{
return false;
}
2025-11-13 11:16:31 +08:00
2026-03-16 18:33:06 +08:00
var firstComponent = ResolveBoundObject(bindData.Objs[0], bindData.ComponentType);
if (firstComponent == null)
2025-11-13 11:16:31 +08:00
{
2026-03-16 18:33:06 +08:00
return false;
2025-11-13 11:16:31 +08:00
}
2026-03-16 18:33:06 +08:00
if (!field.FieldType.IsInstanceOfType(firstComponent))
2025-11-13 11:16:31 +08:00
{
Debug.LogError($"Field {field.Name} type mismatch");
2026-03-16 18:33:06 +08:00
return false;
2025-11-13 11:16:31 +08:00
}
2026-03-16 18:33:06 +08:00
field.SetValue(targetComponent, firstComponent);
return true;
}
private static object ResolveBoundObject(GameObject source, Type componentType)
{
if (source == null || componentType == null)
{
return null;
}
return componentType == typeof(GameObject) ? source : ResolveAssignableComponent(source, componentType);
}
private static Component ResolveAssignableComponent(GameObject source, Type componentType)
{
if (source == null || componentType == null || !typeof(Component).IsAssignableFrom(componentType))
{
return null;
}
Component component = source.GetComponent(componentType);
if (component != null)
{
return component;
}
Component[] components = source.GetComponents<Component>();
for (int i = 0; i < components.Length; i++)
{
Component candidate = components[i];
if (candidate != null && componentType.IsInstanceOfType(candidate))
{
return candidate;
}
}
return null;
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();
2025-11-13 11:16:31 +08:00
return prefabStage?.IsPartOfPrefabContents(go) == true;
2025-11-10 16:01:53 +08:00
}
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);
2025-11-13 11:16:31 +08:00
var isRegularPrefab = assetType == PrefabAssetType.Regular ||
assetType == PrefabAssetType.Variant ||
assetType == PrefabAssetType.Model;
2025-11-10 16:01:53 +08:00
2025-11-13 11:16:31 +08:00
return isRegularPrefab || IsEditingPrefabAsset(go);
2025-11-10 16:01:53 +08:00
}
}
2025-09-05 19:46:30 +08:00
}
}