Using C# attributes to Add Special Behavior to the Unity’s Inspector Window

A C# attribute is a mark that can be placed before a variable within a script to add some special behavior. There are a lot of attributes created to interact with the UnityEngine and UnityEditor namespaces.

This example is focused on some attributes that help us to add features to the inspector window. So when we create a GameObject and attach a script with some variables to it that’s what we see in the inspector window.

Script with some variables
What the inspector shows

Adding C# attributes:

The syntax to add a C# attribute is place the attribute name before the variable declaration between brackets:

[Attribute]public int variable;
  • HideInIspector: allows us to hide a public variable from the inspector.
e.g.[HideInInspector]public int score = 0;
  • SerializeField: forces Unity to serialize a private field and show it in the inspector, very useful when you want to keep a variable private but allow the designer to modify the value.
e.g.[SerializeField]private int _shield = 3;
  • Min: set the min value for a float or int variable.
e.g.[Min(3)]private float _jumpForce = 8f;
  • Range: define a range of values for an int or float variable.
e.g.[Range(0,5)]private float _speed = 5f;
  • Header: allows to put a header above some fields in the inspector.
e.g.[Header(“Health Settings”)]

Adding all of them we can have a result like this in the inspector.

Variables with attributes

Unity offers more attributes that you can use for the inspector and others functionality, below I left you a link with all about attributes in the Unity docs.

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.