Unity中GapRange滑块编辑器显示NaN问题求助
问题解决:自定义GapRange Attribute滑块显示NaN的修复
问题根源
- 错误的PropertyDrawer构造函数:初始版本中自定义了带参数的构造函数,Unity编辑器会自动创建PropertyDrawer实例,不会调用自定义的带参构造,导致
minRange、maxRange等变量未正确初始化,进而引发滑块读取属性值时出现NaN。 - 硬编码参数未关联Attribute:修改后的版本硬编码了范围值,没有从
GapRangeAttribute中读取用户在字段上设置的参数(比如你在CubeSpawner里设置的0,100,0.1f),同时也未处理属性值可能的NaN异常。
修正后的PropertyDrawer代码
using UnityEditor; using UnityEngine; [CustomPropertyDrawer(typeof(GapRangeAttribute))] public class GapRangeDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // 获取对应的GapRangeAttribute实例 var gapRangeAttr = attribute as GapRangeAttribute; if (gapRangeAttr == null) { EditorGUI.LabelField(position, label.text, "Invalid GapRangeAttribute"); return; } if (property.propertyType == SerializedPropertyType.Float) { EditorGUI.BeginProperty(position, label, property); // 处理属性值为NaN的情况,设置默认值为Attribute的最小值 if (float.IsNaN(property.floatValue)) { property.floatValue = gapRangeAttr.minRange; } // 绘制滑块,使用Attribute中定义的范围 EditorGUI.Slider(position, property, gapRangeAttr.minRange, gapRangeAttr.maxRange, label); // 应用灵敏度控制的取整逻辑 property.floatValue = RoundValue(property.floatValue, gapRangeAttr.sensitivity); EditorGUI.EndProperty(); } else { EditorGUI.LabelField(position, label.text, "仅支持float类型字段使用[GapRange]!"); } } private float RoundValue(float value, float sensitivity) { // 避免灵敏度为0的除法错误 if (sensitivity <= 0) return value; return Mathf.Round(value / sensitivity) * sensitivity; } }
关键修正点
- 正确获取Attribute参数:通过
attribute as GapRangeAttribute获取用户在字段上标记的范围和灵敏度,而非硬编码或自定义构造函数。 - NaN值处理:检测到
property.floatValue为NaN时,自动设置为Attribute定义的最小值,避免显示异常。 - 鲁棒性优化:在RoundValue方法中添加灵敏度为0的判断,防止除法错误。
- 还原灵敏度逻辑:重新启用取整代码,确保滑块调节时按照设定的灵敏度步进。
验证效果
将修正后的PropertyDrawer替换原有代码后,CubeSpawner中的gap字段会正常显示0-100范围的滑块,调节时按0.1的步进变化,Inspector面板不再出现NaN。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

