Runtime attributes

Hello,
Can anyone tell me if it is possible to retrieve data from attributes at run-time like if the attribute is used over a function or a class than then we could access all these properties in game through other scripts??:face_with_spiral_eyes::face_with_spiral_eyes:
Thanks in advance:)

yes, but you will need to use reflection to inspect each function or class.

Can you please give an example, I am a bit new to attributes

I had come across a pretty interesting implementation myself. I’ll try and explain it best I can. This is done to provide enums with attributes but It can be easily modified.

// Enums may be set up as follows, with their attributes assigned.
public enum MyEnum
{
    [EnumAttr(false, 1)] EnumValue1, 
    [EnumAttr(true, 2)] EnumValue2,
}

// Create our attribute class
class EnumAttr : Attribute {
    internal EnumAttr(bool EnumBool, int EnumInt){
        this.EnumBool = EnumBool;
        this.EnumInt = EnumInt;
    }
    public bool EnumBool;
    public int EnumInt;
}

// Static class used to retrieve an EnumAttr object.
// From object, the defined attributes can be accessed.

public static class EnumAttribute {
    private static EnumAttr GetAttr(MyEnum myEnum){
        return (EnumAttr)Attribute.GetCustomAttribute (ForValue (myEnum), typeof(EnumAttr));
    }

    private static MemberInfo ForValue(MyEnum myEnum){
        return typeof(MyEnum).GetField (Enum.GetName (typeof(MyEnum), myEnum));
    }
}
2 Likes