In the last blog post we talked about RequireComponent and OnValidate, which help you fail fast.
Fail fast means detecting problems early rather than when the game is already running.
In this blog we’ll talk about Unity attributes used for data validation that help us catch issues in the Inspector itself.
🤔What are Attributes?
An attribute tells the Editor how to behave with the fields, classes, or methods to which it is attached, without writing extra code.
There are many attributes for different purposes such as:
reference safety
serialization
Inspector visualization
In this blog we’ll focus only on the ones used for data validation and safer data entry.
⚠️Important Note
These attributes do not enforce rules at runtime.
They only validate data inside the Inspector.
If you change values through code, these attributes will not stop invalid data.
For runtime safety, you still need validation logic in your scripts.
✏️Data Validation Attributes
1) [Min()]
This attribute restricts an int or float to a minimum value in the Inspector.
[Min(0)] public int health; //prevents negative values from being entered through the Inspector.
2) [Range()]
This attribute restricts a value to a specific range and also shows it as a slider in the Inspector.
[Range(0, 100)] public float volume; // No negative values and nothing above 100.
3) [Tooltip()]
This displays a message when you hover over a field in the Inspector.
[Tooltip("Represents the current health of the enemy")]
public int enemyHealth = 100;
4) [Header()]
Adds a header to group related fields.
This improves readability and reduces the chances of assigning wrong values.
[Header("General Popup settings")]
public float popupAppearDuration = 0.5f;
public float popupStayDuration = 2f;
public float popupDisappearDuration = 0.5f;
5) [Space()]
Adds spacing between fields to make the Inspector cleaner.
public AudioMixer audioMixer;
[Space(20)]
public AudioMixerSnapshot muteSnapshot;
public AudioMixerSnapshot defaultSnapshot;
[Space(20)]
public AudioSource gameWonAudio;
public AudioSource gameOverAudio;
🖼️Checkout these screenshots of inspector window
💡Key Takeaway
These attributes won’t stop bad code, but they will stop bad data from being entered in the Inspector and that alone prevents a lot of bugs.
Fail Fast is not just about catching null references.
It’s also about guiding the user so wrong values are never entered in the first place.


Top comments (0)