编辑器扩展基础4——自定义Attribute

2019-02-19  本文已影响0人  JervieQin

描述

虽然unity为我们准备了很多Attribute(官方文档UnityEnginee/UnityEditor下的Attribute可查看)来供我们修改组件面板的UI,但是有的时候我们想自定义一个外观,这时候我们就能够通过自定义Attribute来个性化。

查阅官方API描述

那么打开api手册我们能够发现如果要自定义属性,那么,我们的属性必须继承自PropertyAttribute,然后与PropertyDrawer连用,以达到自定义属性在Inspector面板上的显示方式。先了解完自定义属性然后,我们再具体看看自定义属性绘制器怎么工作的。前文:自定义PorpertyDrawer

案例

区别于系统自带的[Range],我们自定义一个[RangeAttribute]。
步骤和之前的序列化类差不多。

public class LabelAttribute : PropertyAttribute
{
    public string label;
    public LabelAttribute(string label)
    {
        this.label = label;
    }
}
using UnityEngine;
using UnityEditor;
using System;

[CustomPropertyDrawer(typeof(LabelAttribute),false)]
public class LabelDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        label.text = (attribute as LabelAttribute).label;
        EditorGUI.PropertyField(position, property, label);
    }
}
public class Chinese : MonoBehaviour {
         [LabelAttribute ("中文属性名")]//修改的Property的名字,即原来Inspector中显示的“TestInt”变成了“中文属性名”
        public int testInt;
    
        [Header("中文")]  //内置的Header标签只是在Property上方添加了label,注意和上面的区别
        public string Name;
}
效果

接着讲CustomPropertyDrawer的另一种:DecoratorDrawer

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

上一篇下一篇

猜你喜欢

热点阅读