Unity编辑器拓展PropertyDrawer——Editor绘制偷懒神器

写在前面

我们在使用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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值