Unity泛型类PropertyDrawer继承匹配异常问题求助
解决建议
问题原因
Unity的CustomPropertyDrawer在处理泛型类的继承匹配时,当多个Drawer开启includeChildren=true时,会按照Drawer的编译/注册顺序选择匹配项,而非依据继承层次的接近程度。你给A<>绑定的ADrawer会优先匹配所有A<T>的子类(包括E),即使存在更具体的DDrawer或EDrawer。
1. 调整Drawer优先级(推荐)
使用[DrawerPriority]属性为更具体的Drawer设置更高优先级,让Unity优先选择它们:
[CustomPropertyDrawer(typeof(A<>), true)] public class ADrawer : PropertyDrawer { } [DrawerPriority(DrawerPriorityLevel.PropertyDrawer + 1)] [CustomPropertyDrawer(typeof(D<>), true)] public class DDrawer : PropertyDrawer { } [DrawerPriority(DrawerPriorityLevel.PropertyDrawer + 2)] [CustomPropertyDrawer(typeof(E), true)] public class EDrawer : PropertyDrawer { }
优先级数值越高,越会被优先选中,确保EDrawer > DDrawer > ADrawer的匹配顺序。
2. 限制顶层泛型Drawer的匹配范围
去掉A<>的includeChildren=true,通过拆分继承链缩小ADrawer的匹配范围:
// 新增中间类,区分非D系列的A子类 public class NonDA<T> : A<T> { } // B、C改为继承NonDA<T> public class B : NonDA<int> { } public class C : NonDA<float> { } // ADrawer绑定到NonDA<>,仅处理非D系列子类 [CustomPropertyDrawer(typeof(NonDA<>), true)] public class ADrawer : PropertyDrawer { } // DDrawer仍绑定到D<>,处理其所有子类 [CustomPropertyDrawer(typeof(D<>), true)] public class DDrawer : PropertyDrawer { }
这样E作为D<int>的子类,只会匹配DDrawer,不会被ADrawer捕获。
3. 清除Editor缓存
如果添加EDrawer后仍未生效,可能是Unity Editor缓存问题:
- 关闭Unity,删除项目根目录下的
Library文件夹 - 重新打开项目,让Unity重新编译所有代码
内容的提问来源于stack exchange,提问作者ProtoTyPus
相关产品推荐
相关产品推荐

