Unity自定义Inspector属性名特性以及特性自定义布局问题

前言:

在Unity中编辑属性的适合,一般都是显示属性的英文,如果想要改成中文的话又不能改变属性名,那么自定义特性是很好的选择。

一、自定以特性

这一块没有什么要多说的,就是自定义特性

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class FieldNameAttribute : PropertyAttribute
{
    internal string Name { get; private set; }
    public FieldNameAttribute(string name)
    {
        Name = name;
    }
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(FieldNameAttribute))]
public class FieldNameAttributeDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.PropertyField(position, property, new GUIContent((attribute as FieldNameAttribute).Name), property.hasChildren);
    }
}
#endif

二、布局问题

这样写其实以及完成了效果,如图:

问题一目了然是吧,虽然定义了属性,但我们没有处理其可见子元素的布局

我们只要重写PropertyDrawer中的GetPropertyHeight函数即可

public class FieldNameAttributeDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.PropertyField(position, property, new GUIContent((attribute as FieldNameAttribute).Name), property.hasChildren);
    }
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        float baseHeight = base.GetPropertyHeight(property, label);
        if (property.isExpanded)
        {
            if (property.propertyType == SerializedPropertyType.Generic)
            {
                return baseHeight + EditorGUIUtility.singleLineHeight * property.CountInProperty();
            }
        }
        return baseHeight;
    }

}

如图: