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

Size matters

How to build a search engine ?

Devlog — Week 8

AWS API GATEWAY USE CASES

Lessons I’ve learned from 2.5 years of Software Engineering

Five Things About Software Engineering I Wish I Knew When I Started

BEST EMAIL MARKETING TOOL

✨Integrating LVM with Hadoop and providing Elasticity to DataNode Storage✨

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

Adding a player ammo indicator to the UI

Creating a Simple Cooldown System In Unity

Unity Feature 101: Basic Saving Using PlayerPrefs

Working with Screen Space Reflections in Unity’s HDRP