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

Unity编辑器报MissingMethodException:GapRangeDrawer无默认构造函数的解决

错误含义

MissingMethodException: Default constructor not found for type GapRangeDrawer 表示Unity在尝试实例化你的GapRangeDrawer(自定义属性绘制器)时,找不到无参数的默认构造函数。

Unity的PropertyDrawer体系要求所有自定义绘制器必须提供无参构造——因为Unity内部会通过反射自动创建绘制器实例,不会传入任何参数。如果你的GapRangeDrawer类只定义了带参数的构造函数,就会触发这个异常。

解决步骤

1. 修正构造函数写法

检查GapRangeDrawer的代码,确保它没有自定义带参数的构造函数,或者补充一个无参构造。同时,不要通过构造函数接收GapRangeAttribute实例,正确的方式是通过PropertyDrawer自带的attribute字段获取:

错误示例(会触发异常):

public class GapRangeDrawer : PropertyDrawer {
    private GapRangeAttribute _myAttr;

    // 自定义带参构造,无默认无参构造
    public GapRangeDrawer(GapRangeAttribute attr) {
        _myAttr = attr;
    }
}

正确示例:

// 必须标记该绘制器对应的属性类
[CustomPropertyDrawer(typeof(GapRangeAttribute))]
public class GapRangeDrawer : PropertyDrawer {
    // 无需自定义构造,Unity自动初始化
    private GapRangeAttribute _gapRangeAttr => attribute as GapRangeAttribute;

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        // 直接使用_gapRangeAttr获取属性的配置参数
        float minValue = _gapRangeAttr.Min;
        float maxValue = _gapRangeAttr.Max;

        // 编写你的属性绘制逻辑...
        EditorGUI.Slider(position, property, minValue, maxValue, label);
    }
}

2. 检查访问修饰符与特性标记

  • 确保GapRangeDrawer的访问修饰符是public,否则Unity无法通过反射实例化它。
  • 必须在GapRangeDrawer类上方添加[CustomPropertyDrawer(typeof(GapRangeAttribute))]特性,明确它负责绘制哪一个自定义属性。

3. 清理Unity缓存(可选)

如果修正代码后仍报错,可能是Unity编译缓存导致的:

  • 在Unity编辑器的Project窗口右键,选择Reimport All重新导入所有资源。
  • 关闭Unity,删除项目根目录下的Library文件夹,重新打开Unity让它重新生成缓存。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:07:09