分享

Unity 属性绘制器

 勤奋不止 2023-01-30 发布于北京

描述

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

查阅官方API描述

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

案例

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

  • 实现一个自定义的属性类继承自PropertyAttribute
  • 实现对应的PropertyDrawer并保存在Editor目录下
  • 组件中调用
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;
}
效果

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多