Attributes are a useful feature of C# which allows additional customization to be applied to variables and methods.
Attributes in C# and Unity:
C# has a large number of Attributes which can be applied to variables and methods. To do this, surround the Attribute keyword/s with square brackets (“[ ]”) prior to writing the variable/method.
Most Attributes are part of a namespace, such as “System” or “UnityEngine”.
Multiple attributes can also be applied to one variable or method.
Some common Attributes:
- [Serializable]: Part of the System namespace. Forcefully marks a non-serialized class as serialized, so that all private and public fields are serialized by default.
- [Obsolete]: Part of the System namespace. Marks a field as obsolete, indicating that it is outdated and usage should be avoided. Also adds a helpful tooltip that appears when referencing the obsolete field from another part of code.
- [Flags]: Part of the System namespace. Indicates that an enumeration can be treated as a bit field; that is, a set of flags. In more understandable terms, it allows you to select/combine multiple enums from an enum list, instead of being limited to just one selected enum.
In my next few posts, I will be going into some more Unity-specific Attributes, and also how you can create your own Attributes to make some really useful effects in the Unity Inspector.