using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.UIElements; namespace BITKit.UX { [AttributeUsage(AttributeTargets.Field|AttributeTargets.Property)] public class UXBindPathAttribute : Attribute { public string Path; public bool CanBeNull; public UXBindPathAttribute(){} public UXBindPathAttribute(string path) { Path = path; } public UXBindPathAttribute(string path,bool canBeNull) { Path = path; CanBeNull = canBeNull; } } public class UXUtils { public static void Inject(object self) { UIDocument document; var field = self.GetType().GetField("document", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); switch (field) { case null when self is MonoBehaviour monoBehaviour && monoBehaviour.TryGetComponent(out document): break; case not null when field.GetValue(self) is UIDocument _document: document = _document; break; default: BIT4Log.Warning($"document 未赋值或未找到"); return; } foreach (var fieldInfo in self.GetType() .GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(x=>x.GetCustomAttribute() is not null) ) { var bindPathAtt = fieldInfo.GetCustomAttribute(); VisualElement ve = document.rootVisualElement; foreach (var path in bindPathAtt.Path.Split(".")) { ve = ve.Q(path); } //ve = document.rootVisualElement.Q(bindPathAtt.Path); if(bindPathAtt.CanBeNull is false && ve is null) BIT4Log.LogException(new NullReferenceException($"未找到{bindPathAtt.Path}")); if (fieldInfo.FieldType == typeof(UXContainer)) { fieldInfo.SetValue(self, new UXContainer(ve)); } else { fieldInfo.SetValue(self, ve); } } // if (field.GetValue(self) is not UIDocument _document) // { // if (self is MonoBehaviour monoBehaviour && (document = monoBehaviour.GetComponentInParent())) // { // field.SetValue(self,document); // } // else // { // BIT4Log.Warning($"document 未赋值"); // return; // } // } } } }