只需要将gomeobject的名称与代码中的字段对应就可以实现一键赋值,效果如下
using UnityEngine;
using System.Reflection;
using System.Linq;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(UIBase), true)]
public class UIBaseEditor : Editor
{
public override void OnInspectorGUI()
{
if (GUILayout.Button("一键赋值"))
{
System.Type _type = target.GetType();
FieldInfo[] infos = _type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
System.Type _ComponentType = typeof(Component);
List<KeyValuePair<string, System.Type>> fieldDict = infos.
Where(x => FilterFieldInfo(x, _ComponentType)).
Select(x => new KeyValuePair<string, System.Type>(x.Name, x.FieldType)).ToList();
UIBase ui = target as UIBase;
Transform[] children = ui.transform.GetComponentsInChildren<Transform>();
for (int i = 0; i < fieldDict.Count; i++)
{
foreach (var item in children)
{
if (fieldDict[i].Key.ToLower() == item.name.ToLower())
{
SerializedProperty sp = serializedObject.FindProperty(fieldDict[i].Key);
Component component = item.GetComponent(fieldDict[i].Value);
if (component != null)
{
sp.objectReferenceValue = component;
}
break;
}
}
}
serializedObject.ApplyModifiedProperties();
}
}
bool FilterFieldInfo(FieldInfo info, System.Type baseType)
{
if (info.FieldType.IsSubclassOf(baseType))
{
object[] arr = info.GetCustomAttributes(typeof(SerializeField), true);
if (info.IsPublic || (arr != null && arr.Length > 0))
{
return true;
}
}
return false;
}
}