I have made a basic custom attribute which looks like this:
[System.AttributeUsage(System.AttributeTargets.All)]
public class TestAttribute : System.Attribute
{
private int foo;
public TestAttribute(int testInt)
{
foo = testInt;
}
}
And one of my fields got this attribute assigned like this
[TestAttribute(0)]
public int bar;
Now the part which I do not understand, when I try to get all Attributes of the int “bar” I get all 3 Unity default ones but not the “TestAttribute”, what obvious mistake am I makeing?
How do you try to retrieve it?
Just like this,
object[] rAttr = bar.GetType().GetCustomAttributes(false);
the object array contains “System.Runtime.Interop…”, “System.Reflection.Default…” and “System.SerializableAttribute” but not my custome one. Tried setting the false to true, getting only my attribute and so on, it’s like it never getting assigned.
Because you are looking at the class attribute, not your field.
You will need something like;
public class Foo
{
[TestAttribute(0)]
public int bar;
}
And getting the attribute;
FieldInfo field = typeof(Foo).GetField("bar");
object[] attributes = field.GetCustomAttributes(true);
Works perfectly, thank you.