You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:50:25