Custom Attributes in Unity3D

One of the recent versions of Unity introduced a wider variety of Custom Attributes.

For example, to spice up your boring Editor-exposed floats, you could add the Range-Attribute to get this:

[Range(0.0f, 10.0f)]
public float someVariable = 0.0f;


But how do you create something like that yourself?

The documentation on that is rather sparse, so looking through this blogpost I made myself a Custom Attribute to create a separator line.

The first step is to create a class inherited from PropertyAttribute with public variables of anything you would like to pass to the Attribute. I called mine SeparatorAttribute. Also required is any constructor you plan on using:

  1. public SeparatorAttribute(string _title)
  2. {
  3. this.title = _title;
  4. }


Also, I added a constructor with no parameters.

Next, you’ll need a second class in an editor folder, as it is to be used only be the editor.

There are two variants you can do here now:

The first is a DecoratorDrawer which does not change the original behaviour of the inspector, but extend it.

The second is the PropertyDrawer which overrides the default inspector behaviour. For the purpose of creating a separator-line the former will be sufficient.

  1. [CustomPropertyDrawer(typeof(SeparatorAttribute))]
  2. public class separatorDrawer:DecoratorDrawer

After creating the class and telling it which Attribute it is a Drawer for we can actually do our GUI code by overriding the OnGUI function:

  1. public override void OnGUI(Rect _position)

Inside you can do all the usual GUI code to make it look as pretty as you like.

Also interesting to override is the GetHeight() function to tell the inspector how much space you’ll be needing.

The separators ended up looking like this, called first with no arguments and then with a title:


You can download and test it yourself here.

This entry was posted in Code and tagged , , . Bookmark the permalink.