Unity Tip - The Header Attribute
You might have noticed me using the [Header] Attribute in some of the previous articles (like this one).
In this short article, I’d like to show you what this attribute actually does and why you should use it. Let’s get started!
Let’s take the Player.cs script as an example. To make it easier, I will just use the variables with a [SerializeField] before them, so we just have those that we actually see in the Inspector. We currently have the following variables matching these filters:
In the Inspector, those look like this:
What will removing the Header lead to?
Let’s remove the Header attribute now.
The script will now look like this:
As you can see, the used lines have been reduced. We could even reduce them further by removing the empty lines full of whitespaces. However, it might be more difficult to see where which category of variable is stored with just a quick look at the script.
And inside of Unity, the Inspector will now look like this (in order to avoid any compiler errors, I just created a new script for this):
That does not look very tidy or clean, does it?
Conclusion - Why should you use the Attribute?
For various reasons actually:
- You keep the script file more tidy.
However, you will need more lines of code for this.
- The Inspector will be kept tidy and clean
- Designers will have a much easier job with categories of variables
- You create categories for the variables and assets to assign
That’s it for todays tip! I hope the benefits of using the Header attribute inside of scripts are a bit clearer for you now.