BITFALL/Assets/BITKit/Unity/Scripts/UX/Utils/UXUtils.cs

77 lines
2.0 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit.UX
{
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<UIDocument>(out document):
break;
case not null when field.GetValue(self) is UIDocument _document:
document = _document;
break;
default:
BIT4Log.Warning<UXUtils>($"document 未赋值或未找到");
return;
}
foreach (var fieldInfo in self.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x=>x.GetCustomAttribute<UXBindPathAttribute>() is not null)
)
{
var bindPathAtt = fieldInfo.GetCustomAttribute<UXBindPathAttribute>();
var ve = document.rootVisualElement.Q(bindPathAtt.Path);
if(bindPathAtt.CanBeNull is false && ve is null)
BIT4Log.LogException(new NullReferenceException($"未找到{bindPathAtt.Path}"));
fieldInfo.SetValue(self,ve);
}
// if (field.GetValue(self) is not UIDocument _document)
// {
// if (self is MonoBehaviour monoBehaviour && (document = monoBehaviour.GetComponentInParent<UIDocument>()))
// {
// field.SetValue(self,document);
// }
// else
// {
// BIT4Log.Warning<UXUtils>($"document 未赋值");
// return;
// }
// }
}
}
}