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.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Mongo Spring Multiple Server Config setting

Organizing your UI for performance in Unity

Coding Three Eyed Raven

Automatization with JavaScript using Playwright.

Use Jenkins to Automate Project Versioning

Jenkins Logo

Uninstall Sitecore 9.X Manually

Finishing Touches to Our Terraform Config

Stable Dependencies Principle (SDP)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rusben Guzman

Rusben Guzman

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

More from Medium

3rd Person Follow Virtual Camera Explained in Unity’s Cinemachine

Gamedev Log: “Slash’n’crack” #8 (Unity/C#)

Quick and Easy: Alter Your Pre-Built Unity Texture Maps using Krita.

Rapid Prototyping with the New Input System in Unity 2021