嵌套属性抽屉缩进混乱:Unity自定义ToggledFloat属性绘制异常
解决Unity自定义PropertyDrawer嵌套缩进混乱问题
我之前也碰到过一模一样的情况!问题出在Unity的PropertyDrawer在处理嵌套属性时,父属性会自动增加EditorGUI.indentLevel缩进层级,但你的自定义Drawer没有正确继承和应用这个层级,导致绘制的内容和父类属性的标签不对齐。
问题根源
当ToggledFloat嵌套在ClassWIthNestedProp里时,Unity编辑器会为aTogFloat这个父属性自动添加缩进,但如果你的自定义Drawer忽略了EditorGUI.indentLevel,绘制的复选框和数值框就会直接左对齐,和父属性的标签脱节。
修复后的PropertyDrawer实现
下面是能正确处理嵌套缩进的完整Drawer代码,我会标注关键细节:
using UnityEditor; using UnityEngine; [CustomPropertyDrawer(typeof(ToggledFloat))] public class ToggledFloatDrawer : PropertyDrawer { // 绘制属性的核心方法 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // 开始属性绘制上下文,确保Unity的编辑器状态正确 EditorGUI.BeginProperty(position, label, property); // 使用Scope自动管理缩进层级,避免手动恢复时出错 using (new EditorGUI.PropertyScope(position, label, property)) using (new EditorGUI.IndentLevelScope()) // 继承父属性的缩进层级 { // 获取ToggledFloat的两个子属性 SerializedProperty enabledProp = property.FindPropertyRelative("enabled"); SerializedProperty valueProp = property.FindPropertyRelative("value"); // 用水平布局排列复选框和数值输入框 using (new EditorGUILayout.HorizontalScope()) { // 绘制enabled复选框,不显示标签,固定宽度避免挤压 EditorGUILayout.PropertyField(enabledProp, GUIContent.none, GUILayout.Width(20)); // 绘制value字段,显示属性的原始标签,自动填充剩余宽度 EditorGUILayout.PropertyField(valueProp, label); } } EditorGUI.EndProperty(); } // 确保属性高度和默认单行属性一致,避免布局错乱 public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return EditorGUIUtility.singleLineHeight; } }
关键细节说明
EditorGUI.IndentLevelScope():这个Scope会自动继承当前的缩进层级,嵌套时自动对齐父属性的缩进,不用手动修改和恢复EditorGUI.indentLevel,避免遗漏导致后续布局出错。- 水平布局:用
EditorGUILayout.HorizontalScope()把复选框和数值框放在同一行,保持和Unity默认属性的布局风格一致。 - 固定复选框宽度:给
enabled复选框设置固定宽度GUILayout.Width(20),避免数值框挤压复选框,保证布局稳定。 - 统一高度:重写
GetPropertyHeight返回默认单行高度,确保嵌套时不会出现多余的空白或重叠。
替换你原来的PropertyDrawer代码后,不管是直接在Test类里的tF属性,还是嵌套在ClassWIthNestedProp里的aTogFloat,都会正确显示缩进,布局完全对齐。
内容的提问来源于stack exchange,提问作者sune
相关产品推荐
相关产品推荐

