你可以創建自己的屬性來添加特定的元數據或行為。創建自定義屬性需要繼承 System.Attribute
並使用 [AttributeUsage]
指定屬性可以應用到哪些目標。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
public string Description { get; }
public MyCustomAttribute(string description)
{
Description = description;
}
}
如何自製作自己的 Attribute:
using System;
using System.Reflection;
using UnityEngine;
public class DataNameAttribute : Attribute
{
public string PropName;
}
在需要更換名字的變數上加入DataName的Attribute,
複寫ToString的函式
public class Character
{
[DataName(PropName = "LifePoint")]
public int Hp { get; set; }
[DataName]
public int Mp { get; set; }
public override string ToString()
{
string str = "";
foreach (PropertyInfo info in GetType().GetProperties())
{
foreach (Attribute attr in Attribute.GetCustomAttributes(info))
{
if (attr.GetType() == typeof(DataNameAttribute))
{
var propName = ((DataNameAttribute)attr).PropName;
if (propName != null)
str += ((DataNameAttribute)attr).PropName + ":" + info.GetValue(this) + " ";
else
str += info.Name + ":" + info.GetValue(this) + " ";
}
}
}
return str;
}
}
public class CharacterData : MonoBehaviour
{
private void Start()
{
Character character = new Character();
character.Hp = 100;
character.Mp = 200;
Debug.Log(character);
}
}
5.顯示結果: