写在前面
我们在使用UnityEditor自定义属性面板时,大多的时候都是直接使用继承Editor的方式实现,一个脚本类写一个Editor类,但是有很多非MonoBehaviour的类,会需要在不同的脚本上使用,这个时候需求就来了,每一个都要重复写那也太麻烦了,这个时候就可以用PropertyDrawer了。
我使用的Unity版本:Unity 2020.3.10
总结
PropertyDrawer的两大主要作用:
1. 用于自定义绘制可序列化的类或结构体
有需要自定义显示的又会可能在多个脚本中使用到的类或结构体都可以使用PropertyDrawer来实现,PropertyDrawer如其名,就像一个专门的属性绘制器一样,对一个类或结构体进行自定义属性绘制后,当脚本在属性面板上显示该属性时,就会调用到该自定义的绘制,不用我们再写Editor脚本去单独绘制,所以省去了大量的工作
2. 搭配PropertyAttribute可自定义Attribute
相信大家平常都有用过诸如【Header】【ToolTip】之类的Attribute,而通过PropertyAttribute+PropertyDrawer就可以自定义自己的Attribute
自定义绘制可序列化的类或结构体
这里我们使用书,书单的类来示例这个功能
Book就是我们要进行自定义绘制的类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum BookType
{
Novel,
Science,
Life,
Tool,
}
[System.Serializable]
public class Book
{
public string name;
public BookType type;
public string overview;
}
public class BookList : MonoBehaviour
{
public Book currentRead;
public Book[] readList;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(Book))]
public class BookDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property