效果图:
没添加Attribute效果图:
添加Attribute效果图
public class Test:MonoBehaviour{
[MyTest(name = "枚举")]//这里可以用MyTest也可以用MyTestAttribute
public Properties pp = Properties.HP;
[MyTest(name = "整数")]
public int a;
[MyTest(name = "字符串")]
public string c;//这里赋值了name,则使用赋的值:字符串
[MyTest]//这里没有赋值name,则使用字段的名字:d
public bool d;
[MyTest(name = "颜色")]
public Color color;
public void Update(){
if(Input.GetMouseButtonDown(0)){
Debug.Log(pp.ToString() + " " + GetDes(pp));
}
}
//反射获取desc
public static string GetDes(Properties p){
Type type = p.GetType();
FieldInfo[] fields = type.GetFields();
foreach(FieldInfo f in fields){
if(f.Name.Equals(p.ToString())){
object[] objs = f.GetCustomAttributes(typeof(PropertiesDesc),true);
if(objs != null && objs.Length > 0){
return ((PropertiesDesc)objs[0]).Desc;
}
}
}
return p.ToString();
}
}
public Enum Properties{
[PropertiesDesc(Desc = "血量")]
HP,
[PropertiesDesc(Desc = "蓝量")
MP,
[PropertiesDesc(Desc = "防御")]
Def,
[PropertiesDesc(Desc = "速度")]
Speed,
[PropertiesDesc(Desc = "伤害")]
Damage,
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Enum)]
public class PropertiesDesc : Attribute{
public string Desc{get;set;}
}
public class MyTestAttribute : PropertyAttribute{
public string name{get;set;}
}
[CustomPropertyDrawer(typeof(MyTestAttribute))]
public class MyTestDrawer : PropertyDrawer{
public override void OnGUI(Rect position,SerializedProperty property,GUIContent label){
MyTestAttribute range = attribute as MyTestAttribute;
//如果Attribute赋值了name,则使用赋值的值,如果没有赋值,则使用字段的名字
string otherName = "";
if(string.IsNullOrEmpty(range.name)){
otherName = label.text;
}else {
otherName = range.name;
}
if(property.propertyType == SerializedPropertyType.Integer){
EditorGUI.IntSlider(position,property,0,10,otherName);
}else if(property.propertyType == SerializedPropertyType.Float){
EditorGUI.Slider(position,property,0,10,otherName);
}else if(property.propertyType == SerializedPropertyType.Enum){
string strList = new string[property.enumNames.Length];
for(int i=0;i<strList.Length;i++){
strList[i] = Test.GetDes((Properties)i);
}
property.enumValueIndex = EditorGUI.Popup(position,otherName,property.enumValueIndex,strList);
}else if(property.propertyType == SerializedPropertyType.Boolean){
property.boolValue = EditorGUI.Toggle(position,otherName,property.boolValue);
}else if(property.propertyType == SerializedPropertyType.String){
property.stringValue = EditorGUI.TextField(position,otherName,property.stringValue);
}else if(property.propertyType == SerializedPropertyType.Color){
property.colorValue = EditorGUI.ColorField(position,otherName,property.colorValue);
}
}
}
第一次自定义Attribute,如果错误,请提出,会尽快修改。
定义的只是自己需要的,如果不满足你的工程,可以自己拓展。