编辑器扩展基础3-自定义PropertyDrawer

介绍

自定义Unity组件时如果不加以控制,会按照Unity默认的方式来排布显示可序列化属性。

如果我们向让属性显示得更个性化一些,可以自定义PropertyDrawer。

这个PropertyDrawer它可以指定Serializable类(可序列化类)或PropertyAttribute(自定义属性),这样就有了两种使用:

  • 为每个Serializable实例绘制GUI
  • 为自定义属性的每个元素绘制GUI

另注
组件为什么能显示在Inspector面板上?
因为组件都继承自Monobehaviour,父类的initiate方法起到了序列化和反序列化的作用。这样就能保存为MetaData,供下次使用。

Serializable类(可序列化类)在Unity中有什么含义呢?
默认地,Unity只给自定义的公有变量、继承自MonoBehaviour的类执行序列化,所以如果想让一个类序列化,那么就要指定[Serializable]标签。它将MetaData放入可以通过反射重新获取并由Unity使用的类中。有了这个Unity知道它应该/可以序列化类。

Unity序列化的关键字是 Serializable 和 SerializeField,具体描述可以翻阅api。

案例1-将Serializable类的属性按照一定排布方式显示出来

假设我们在写一个组件需要把一个引用字段里的属性都显示出来供配置,那么,根据上面的介绍我们要分两步。

  • 实现可序列化类
  • 实现对应的PropertyDrawer(放在Editor目录下)
  • 组件调用
public enum IngredientUnit { Spoon, Cup, Bowl, Piece }

[Serializable]
public class Ingredient
{
    public string name;
    public int amount = 1;
    public IngredientUnit unit;
}
using UnityEditor;
using UnityEngine;

//给Ingredient指定PropertyDrawer
[CustomPropertyDrawer(typeof(Ingredient))]
public class IngredientDrawer:PropertyDrawer{
    //在给定的Rect区域中绘制属性
    public override void OnGUI(Rect position,SerializedProperty property,GUIContent label){
        //重载BeginProperty
        EditorGUI.BeginProperty(position,label,property);  

        //绘制标签
        position = EditorGUI.PrefixLabel(position,GUIUtility.GetControlID(FocusType.Passive),label);
        
        //Unity默认的每个属性字段都会占用一行,我们这里希望一条自定义Property占一行
        //要是实现这个要求我们分三步: 1. 取消缩进  2. 设置PropertyField 3.还原缩进
        
        //不要缩进子字段,只有取消了缩进,Rect挤才一行才不会混乱
        var indent = EditorGUI.indentLevel;
        EditorGUI.indentLevel = 0;

        //计算要用到的属性显示rect   Rect(x,y,width,height)x,y是左顶点
        var amountRect = new Rect(position.x,position.y,30,position.height);
        var unitRect = new Rect(position.x + 35,position.y,50,position.height);
        var nameRect = new Rect(position.x + 90,position.y,position.width  -  90,position.height);

        //绘制字段 - 将GUIContent.none传递给每个字段,以便绘制它们而不是用标签
        //属性绘制器不支持布局来创建GUI;
        //因此,您必须使用的类是EditorGUI而不是EditorGUILayout。这就是为什么要给每个属性指定Rect
        EditorGUI.PropertyField(amountRect,property.FindPropertyRelative("amount"),GUIContent.none);
        EditorGUI.PropertyField(unitRect,property.FindPropertyRelative("unit"),GUIContent.none);
        EditorGUI.PropertyField(nameRect,property.FindPropertyRelative("name"),GUIContent.none);

        //将缩进还原,好习惯
        EditorGUI.indentLevel = indent;

        EditorGUI.EndProperty();
    }
}
public class Recipe : MonoBehaviour
{
    public Ingredient potionResult;
    public Ingredient[] potionIngredients;
    public Vector2 ff = Vector2.zero;
}

前文链接:自定义menuItem
下文:针对自定义特性创建PropertyDrawer

注:配套案例可在EditorExtensionDemo仓库中查看。

你可能感兴趣的:(编辑器扩展基础3-自定义PropertyDrawer)