Sometimes, when programming our Unity game with C#, we find that the variables we define can make the Inspector screen complex. Attributes, one of the blessings of C#, make our variables more readable. In other words, they help clean up our Inspector screen, making it look neater.
While Attributes generally keep your Inspector screen tidy, their purpose is not limited to that; they can also serve various purposes and conditions in your code.
- [SerializeField]Perhaps the most popular one. It allows us to control private or protected variables only from the Unity Inspector screen. We often use it for variables we don’t want to be accessed from outside.
- [Range(a, b)]Controls the minimum and maximum values a variable can take. ‘a’ represents the minimum value, and ‘b’ represents the maximum value.
- [Header(“”)]This Attribute is used to give titles to variables. For example, by giving titles to Text variables and Image variables, you can achieve a cleaner look.
- [Tooltip(“”)]When the mouse cursor hovers over the variable in the Inspector, it receives a description message. This helps us understand the purpose of the variable.
- [RequireComponent(typeof())]This Attribute automatically adds the required Component for your code to run.
- [ExecuteInEditMode]Runs a MonoBehaviour component in edit mode. With this Attribute, you don’t need to press the Run button for your code to work.
- [HideInInspector]It is the opposite of the [SerializeField] Attribute. While we can’t see the variables in the Inspector, we can access them with other scripts.
- [Obsolete(“”)]Usually written at the beginning of old methods. Its purpose is to give a warning message when developers use the method.
- [ExecuteAlways]Like [ExecuteInEditMode], it runs our MonoBehaviour component in edit mode, but in addition, it runs when we press the Run button.
- [ContextMenu(“”)]Allows us to run a method in the Inspector screen once. It is often used in prototyping.
- [AddComponentMenu(“”)]Determines how it will be listed in the Component menu. By using this Attribute on a component class, you can customize how it appears in the component menu.
- [Space()]Allows us to add space in the Inspector screen.
- [TextArea(a, b)]Enlarges the classic Input Text area in the Inspector screen.
- [Multiline()]Serves almost the same purpose as [TextArea(a, b)], but the only difference is that [Multiline()] takes a single value instead of two.
- [DisallowMultipleComponent]This Attribute is used to specify that a component cannot be added to the same object more than once, ensuring that the component is only added once.
References: