使用自定义属性(实现中文标签)
步骤1:创建 ChineseLabelAttribute.cs
|
1 2 3 4 5 6 7 8 9 10 11 |
using UnityEngine; public class ChineseLabelAttribute : PropertyAttribute { public readonly string Label; public ChineseLabelAttribute(string label) { Label = label; } } |
这段代码定义了一个新的特性(Attribute),名为 ChineseLabelAttribute。它的主要作用是:
- 标记与存储:当你希望一个字段在Unity检视器中显示中文名称时,可以用
[ChineseLabel("中文名称")]来标记这个字段。这个特性类会存储你提供的中文文本。 - 元数据附加:它继承自Unity的
PropertyAttribute,这意味着它可以作为元数据附加到脚本的字段上,用于向Unity编辑器提供额外的信息,但本身并不改变字段的绘制方式 。
步骤2:创建 ChineseLabelDrawer.cs(放在Editor文件夹)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#if UNITY_EDITOR using UnityEditor; using UnityEngine; [CustomPropertyDrawer(typeof(ChineseLabelAttribute))] public class ChineseLabelDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { ChineseLabelAttribute attr = attribute as ChineseLabelAttribute; EditorGUI.PropertyField(position, property, new GUIContent(attr.Label)); } } #endif |
这段代码是一个自定义绘制器(PropertyDrawer),它负责如何绘制被 ChineseLabelAttribute标记的字段。
- 重写绘制逻辑:它继承自
PropertyDrawer并重写OnGUI方法。这个方法决定了属性在检视器中的实际显示样子。 - 替换显示标签:在
OnGUI方法中,它获取字段上ChineseLabelAttribute中存储的中文标签,然后用这个中文文本替换掉原本默认的英文变量名,最后调用EditorGUI.PropertyField来绘制这个字段 。 - 编辑器脚本要求:必须将此类放在项目的
Editor 文件夹下(例如Assets/Editor/ChineseLabelDrawer.cs),否则Unity无法正确识别和编译它。