【问题标题】:Is there a way to get the PropertyDrawer-derived class given a type that has been associated with it using CustomPropertyDrawer?有没有办法让 PropertyDrawer 派生类给定一个已使用 CustomPropertyDrawer 与之关联的类型?
【发布时间】:2022-08-24 13:45:25
【问题描述】:

在 Unity3D 脚本中,有没有办法在给定与使用 CustomPropertyDrawer 关联的类型的情况下获取 PropertyDrawer 派生类?所以在下面的例子中:

using UnityEngine;
using UnityEditor;

public struct MyCustomType {
    ...
}

[CustomPropertyDrawer(typeof(MyCustomType))]
public class MyCustomTypeDrawer : PropertyDrawer {
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        ...
    }
}

...如果给定MyCustomType,此方法将返回MyCystomTypeDrawer(最好是Type)。但它是通用的,适用于使用CustomPropertyDrawer 与之关联的PropertyDrawer 派生类的任何类型。

  • 你绝对可以使用反射。浏览所有加载的程序集,查看每个声明的类型,并检查该类型是否扩展了 PropertyDrawer。然后,您需要获取传递给 CustomPropertyDrawerAttribute 的类型(内部类型 m_Type),然后检查该类型是否与传递给您的函数的类型相同。

标签: c# unity3d


【解决方案1】:

继@hijinxbassist 的评论之后:这是我的实现:

IEnumerable<System.Type> AllPropertyDrawers()
{
    List<System.Type> drawers = new List<Type>();
    foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
    {
        foreach (Type t in ass.GetTypes())
        {
            if (t.IsSubclassOf(typeof(PropertyDrawer)))
            {
                yield return t;
            }
        }
    }
}
System.Type GetCustomPropertyDrawerFor(System.Type target)
{
    foreach (Type drawer in AllPropertyDrawers())
    {
        foreach (var attribute in Attribute.GetCustomAttributes(drawer))
        {
            if (attribute is CustomPropertyDrawer cpd)
            {
                if (target.IsSubclassOf(cpd.GetPrivateMemberUsingReflection<Type>("m_Type")))
                {
                    return drawer;
                }
            }
        }
    }

    return null;
}

【讨论】:

    猜你喜欢
    • 2010-11-22
    • 2017-04-10
    • 2014-07-29
    • 2021-07-24
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多