Unity3D CustomPropertyDrawer 自定义属性绘制器
-
- 该文档中的
EditorGUI.BeginProperty()
和EditorGUI.EndProperty()
,不好用
- 该文档中的
-
参考案例:
- 直接看Unity中你感兴趣的渲染方式的实现方式:
Packages/com.unity.ugui/Editor/UI/PropertyDrawers/...
FontDataDrawer
SpriteStateDrawer
ColorBlockDrawer
NavigationDrawer
- 也可以直接在
Project
视图搜索Drawer
,搜索范围选择In Packagers
- 直接看Unity中你感兴趣的渲染方式的实现方式:
-
需要做的事
- 绘制
- 重写
GetPropertyHeight
返回真正的高度- 不要忘记标题占了1行
- 考虑展开 / 收缩 的情况, 返回不同的高度,
- 收缩时,高度=
EditorGUIUtility.singleLineHeight
- 展开时,高度=
EditorGUIUtility.singleLineHeight
+ 标题以外所有内容的高度 + 行间距*(行数-1)
- 收缩时,高度=
-
基本常识:
OnGUI(Rect position, SerializedProperty property, GUIContent label)
中position
是这个变量的起始位置property
是这个变量的SerializedProperty
对象- 通过这个对象,可以获取到变量的值
property.FindPropertyRelative(paramName).(intValue / stringValue / vector3Value / enumValueIndex / ...)
- 通过这个对象,可以获取到变量的值
lable.text
是变量名称
- 默认每行高度是:
EditorGUIUtility.singleLineHeight
- 默认行间距是:
EditorGUIUtility.standardVerticalSpacing
- 想要缩进/反缩进 1个单位, 可以使用:
EditorGUI.indentLevel++
和EditorGUI.indentLevel--
- 对于不需要自定义渲染方式的字段 使用
EditorGUI.PropertyField
执行默认的渲染方案, - 所有要绘制的内容,推荐使用
EditorGUI
类, 而不是GUI
类EditorGUI
类的方法, 会自动处理缩进的问题GUI
类的方法, 不会自动处理缩进的问题- 比如
GUI.Button(rect, "↑"))
,不受缩进的影响,所有要额外把rect.x
加上缩进的距离35
比较合适
- 比如
-
小技巧
- 绘制展开 / 折叠按钮
- 使用
EditorGUI.Foldout
->if (foldout = EditorGUI.Foldout(rect, foldout,$"{label.text} 更多内容:{}")
- 标题行除了显示变量名称以外, 其实可以显示更多信息, 以便在没有展开的情况下就可以把 关键信息 显示到标题行的标题后面
- 使用
- 绘制展开 / 折叠按钮
-
⚠️ 注意:
- 必须十分清除, 自己的绘制方案, 占用了多少高度, 否则会出现绘制不全的情况
- 绘制时
- 关于
layout
周边的方法- 在
EditorGUI.BeginProperty()
和EditorGUI.EndProperty
包裹的范围里,不可以使用layout
相关的方法, 否则会报错:ArgumentException: Getting control 1's position in a group with only 1 controls when doing repaint
- 在
EditorGUI.BeginProperty()
外面, 执行layout
相关的方法, 不生效不显示
- 在
- 关于