一、效果图
测试代码也是很简单就是添加了几个变量
这里的 SerializeField 特性主要是在Inspector面板显示private 的变量
在代码中照样是用name,age,address,time这几个变量。
二、脚本内变量
using UnityEngine;
public class LableTest : MonoBehaviour
{
[SerializeField, Label("姓名")] private string name = "老王";
[SerializeField, Label("年龄")] private int age = 100;
[SerializeField, Label("地址")] private string address = "深圳";
[SerializeField, Label("时间[秒]")] private float time = 5;
}
三、编辑器脚本
//第一个建议存放目录:Assets/Scripts/Utility/LabelAttribute.cs
//注意这个LabelAttribute.cs千万不要放在Editor文件夹下,否则会报错找不到Label("姓名")这个特性。
using UnityEngine;
public class LabelAttribute:PropertyAttribute
{
private string name = "";
public string Name { get { return name; } }
public LabelAttribute(string name)
{
this.name = name;
}
}
//第二个建议存放目录:Assets/Scripts/Editor/Utility/LabelAttributeDrawer.cs
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(LabelAttribute))]
public class LabelAttributeDrawer:PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
LabelAttribute attr = attribute as LabelAttribute;
if(attr.Name.Length > 0)
{
label.text = attr.Name;
}
EditorGUI.PropertyField(position, property, label);
}
}