EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

C#高级编程——Attribute特性

在Unity中,当你写
[RequireComponent(typeof(Rigidbody))]
的时候,脚本会为你请求Rigidbody,
一旦这个脚本挂上去,
Inspector里面会为你自动增加一个Rigidbody;


当你准备Remove Rigidbody的时候,
会弹出对话框提示你,
Can't Remove Because XXX(script) depends on it.


所以你应当先移除脚本,再移除你所依赖的对象。


像这种,
以中括号形式,写在类、字段或方法前面的,是用来定义目标特性的东西。


不改变方法的内容,主要用于约束和限制。

比如:

[Range(1f, 4f)]float m_GravityMultiplier = 2f;

限制了m_GravityMultiplier只能是1f-4f,

至于具体怎么实现的,我们并不需要关心。

 

 

当然,你也可以查看原定义,
F12到从元数据是这样的:

namespace UnityEngine
{

    [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]

    public abstract class PropertyAttribute : Attribute
    {
        protected PropertyAttribute();

        public int order { get; set; }
    }
}

AttributeUsage()用来定义特性的使用范畴;
AttributeTargets.Field 表示能写在字段前面;
AttributeTargets.Method 表示能写在方法签名;
Inherited=true表示允许继承;
AllowMultiple=true表示允许多个特性;

 

所有的特性都继承 Attribute,
unity在其中多封装了一层 PropertyAttribute ,且给每个特性加上了一个ID


自定义特性定义时,名称后面最好加上“Attribute”后缀,而在使用的时候,可以省略后缀“Attribute”,这个C#会自动判断的。

 

参考文档:

[1] C#中的特性,以及一些思考

[2] 高级程序员面试过程中一定会被问到的Attribute

This article was last edited at 2020-03-25 17:39:43

* *