特性用于添加元数据(描述数据的数据)
可以放在脚本中的“类、属性或函数上方“向程序添加声明性信息,一个程序可添加多个特性;
Unity中常用的特性
- [Header(“name”)] :在 Inspector 中的某些字段上方添加标题
- [Range(min,max)] :使脚本中的float或int类型的变量受限于特定范围,且在Inspector面板中显示为滑动条;
- [HideInInspector] :使变量不显示在Inspector中,但进行序列化(变为二进制字节流,使其状态信息转换为可存储或传输的形式);
- [AddComponentMenu] :在Component菜单中放置脚本,改进添加脚本时的工作流程;
- [RequireComponent(typeof(Component))] :向GameObject添加使用RequireComponent的脚本时,会自动将需要的组件添加到GameObject中;
.NET框架的特性
AttributeUsage预定义特性
描述如何使用一个自定义特性类,规定了特性可应用到的项目的类型;
[AttributeUsage(validon,AllowMultiple=allowmultiple,Inherited=inherited)]
第一个参数:规定特性可被放置的语⾔元素,它是枚举器 AttributeTargets 的值的组合,默认值是 AttributeTargets.All;
第二个参数:表示特性是否可多次使用,通过AllowMultiple=bool进行声明;
第三个参数:表示特性是否可以被继承,通过Inherited=bool进行声明;
注:AttributeUsage特性是单次使用的特性,它无法应用于同一个类超过一次;
自定义特性
自定义特性:用于存储声明性的信息,且可在运行时被检索;
- 声明自定义特性:自定义特性的类应派生自System.Attribute类;
- 构建自定义特性,每个特性必须至少有一个构造函数,用于传递参数;
- 在目标程序元素上应用自定义特性:把特性放置在紧接着它的目标之前即对目标应用特性;
- 通过反射访问特性:(自定义特性不被检索及操作则是没有价值的)使用GetCustomAttributes方法可检索通过自定义特性定义的信息,返回对象数组,这些对象在运行时等效于源代码中的特性;
特性只能通过反射拿到,程序可通过反射检查自己的元数据或其他程序内的元数据:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class MyConditionAttribute : Attribute{
public string author;
public string LastDate;
public MyConditionAttribute(string author){
this.author = author;
}
}
//Attribute可省略
[MyConditionAttribute("Albert", LastDate = "2020.5.13"), MyCondition("Tom", LastDate = "2020.10.13")]
public class UsersAttributes : MonoBehaviour{}
public class UsesAttributeObserver : MonoBehaviour{
private void PrintAttributeMsg(){
Type type = typeof(UsersAttributes);
object[] atts = type.GetCustomAttributes(false);
for (int i = 0; i < atts.Length; i++){
if (atts[i] is MyConditionAttribute){
MyConditionAttribute authorObj = atts[i] as MyConditionAttribute;
Debug.Log(authorObj.author);
Debug.Log(authorObj.LastDate);
}
}
}
}