【Unity】自定义字段在Inspector中显示的名称

【Unity】使字段在Inspector中显示自定义的名称

默认情况下Unity会将字段的名称首字母大写后显示在Inspector面板上,这里通过自定义 PropertyAttributePropertyDrawer 的方式实现了使字段在Inspector面板中显示自定义的名称。自定义的特性可以用于 public 字段,也可以配合 SerializeField 特性作用于 private 字段。

首先实现一个 CustomLabelAttribute 特性,这个特性中包含一个 string 类型的 name 字段,用于指定自定义的字段名称。代码如下:

using UnityEngine;

/// <summary>
/// 使字段在Inspector中显示自定义的名称。
/// </summary>
public class CustomLabelAttribute : PropertyAttribute
{ 
    public string name;

    /// <summary>
    /// 使字段在Inspector中显示自定义的名称。
    /// </summary>
    /// <param name="name">自定义名称</param>
    public CustomLabelAttribute(string name)
    { 
        this.name = name;
    }
}

然后实现一个 CustomLabelDrawer 类,该类中定义了对带有 CustomLabelAttribute 特性的字段的面板内容的绘制行为。需要注意的是, CustomLabelDrawer 类的代码文件应该放到 Editor 文件夹下。代码如下:

using UnityEditor;
using UnityEngine;

/// <summary>
/// 定义对带有 `CustomLabelAttribute` 特性的字段的面板内容的绘制行为。
/// </summary>
[CustomPropertyDrawer(typeof(CustomLabelAttribute))]
public class CustomLabelDrawer: PropertyDrawer
{ 
    private GUIContent _label = null;
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    { 
        if (_label == null)
        { 
            string name = (attribute as CustomLabelAttribute).name;
            _label = new GUIContent(name);
        }

        EditorGUI.PropertyField(position, property, _label);
    }
}

实现了 CustomLabelAttribute 类和 CustomLabelDrawer 类之后,为字段添加 CustomLabel 特性,并在参数中传入要显示的自定义字段名,即可使字段在Inspector中显示自定义的名称。如下图:

《【Unity】自定义字段在Inspector中显示的名称》

    原文作者:Arvin ZHANG
    原文地址: https://blog.csdn.net/qq_21397217/article/details/89212607
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞