PropertyDrawer和PropertyAttribute
Inspector面板的显示编辑的两种方式
PropertyDrawer
介绍
PropertyDrawer官方文档
修改某种特定类型的显示,使用继承Editor
的方式就会变得很麻烦,因为所有使用特定类型的asset都需要去实现一个自定义的Editor,效率非常低。这种情况就可以通过继承PropertyDrawer
的方式,对指定类型的属性,进行统一显示。
示例代码
[CustomPropertyDrawer(typeof(string))]
public class StringPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Rect btnRect = new Rect(position);
position.width -= 60;
btnRect.x += btnRect.width - 60;
btnRect.width = 60;
EditorGUI.BeginProperty(position, label, property);
EditorGUI.PropertyField(position, property, true);
if (GUI.Button(btnRect, "select"))
{
string path = property.stringValue;
string selectStr = EditorUtility.OpenFilePanel("选择文件", path, "");
if (!string.IsNullOrEmpty(selectStr))
{
property.stringValue = selectStr;
}
}
EditorGUI.EndProperty();
}
}
效果
为Inspector面板中的所有string属性添加一个选择文件按钮,选中文件的路径直接赋值给该变量。
注意事项
- PropertyDrawer只对可序列化的类有效,非可序列化的类没法在Inspector面板中显示。
- OnGUI方法里只能使用GUI相关方法,不能使用Layout相关方法。
- PropertyDrawer对应类型的所有属性的显示方式都会修改,例如创建一个带string属性的MonoBehaviour。
PropertyAttribute
介绍
PropertyAttribute官方文档
想要修改部分类的指定类型的属性的显示,直接使用PropertyDrawer就无法满足条件,这时可以结合PropertyAttribute和PropertyAttribute来实现需求。
示例代码
public class RangeAttribute : PropertyAttribute
{
public float min;
public float max;
public RangeAttribute(float min, float max)
{
this.min = min;
this.max = max;
}
}
[CustomPropertyDrawer(typeof(RangeAttribute))]
public class RangeDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
RangeAttribute range = attribute as RangeAttribute;
if (property.propertyType == SerializedPropertyType.Float)
EditorGUI.Slider(position, property, range.min, range.max, label);
else if (property.propertyType == SerializedPropertyType.Integer)
EditorGUI.IntSlider(position, property, (int)range.min, (int)range.max, label);
else
EditorGUI.LabelField(position, label.text, "Use Range with float or int.");
}
}
效果
为部分指定类的int或float属性的显示添加滑动条,滑动条的上下限可根据类和属性自行设置。