自定义Property Drawer报错:NullReferenceException: SerializedProperty为空
解决Unity自定义PropertyDrawer的NullReferenceException问题
问题场景
为自定义类InputAxis实现PropertyDrawer,期望在Inspector中显示枚举下拉菜单,但调用property.FindPropertyRelative("InputEvent")和property.FindPropertyRelative("Axis")时触发NullReferenceException,属性名称和命名空间均确认无误。
排查与解决思路
检查字段序列化权限
Unity的序列化系统仅处理public字段,或带有[SerializeField]标签的非public字段。如果InputAxis中的InputEvent和Axis是private/protected且未加[SerializeField],FindPropertyRelative会返回null。
修正示例:public class InputAxis { public InputEventType InputEvent; [SerializeField] private AxisType Axis; }确保InputAxis类可被序列化
- 若
InputAxis是嵌套类,必须添加[Serializable]标签才能被Unity序列化识别:public class YourMonoBehaviour : MonoBehaviour { [Serializable] public class InputAxis { public InputEventType InputEvent; public AxisType Axis; } } - 避免将
InputAxis标记为[NonSerialized],且不能是静态类或未正确实现序列化的抽象类。
- 若
验证PropertyDrawer的类型关联
确认[CustomPropertyDrawer(typeof(InputAxis))]中的类型完全匹配,若存在命名空间冲突,使用完整命名空间指定:[CustomPropertyDrawer(typeof(YourNamespace.InputAxis))] public class InputAxisDrawer : PropertyDrawer { /* ... */ }修复损坏的序列化数据
若问题出现在已存在的GameObject/ScriptableObject上,可能是序列化缓存损坏:- 移除组件后重新添加
- 右键组件选择
Reset重置属性 - 删除项目根目录的
Library文件夹,重启Unity重新生成缓存
调试确认序列化属性结构
在OnGUI方法中添加调试代码,查看Unity实际能识别的子属性:public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // 调试代码 Debug.Log($"当前属性路径: {property.propertyPath}"); SerializedProperty iterator = property.Copy(); if (iterator.Next(true)) { do { Debug.Log($"子属性名称: {iterator.name}"); } while (iterator.Next(false)); } // 原有逻辑... }通过日志可确认
InputEvent和Axis是否在序列化列表中,排除大小写拼写错误等问题。
内容的提问来源于stack exchange,提问作者Ryan P.
相关产品推荐
相关产品推荐

