If you want to add extra functionality to any UI component in Unity there are a few things to keep in mind. In this post we will go through how to extend the behaviour of a Button by adding an extra field for an overlay.

Why we need a custom inspector

If you inherit from UnityEngine.UI.Button you will find that if you add SerializeField or any public field they will not show in the inspector. This is because the inspector knows what to show for a Button but not for your own specific inherited version. Therefore you will need a custom inspector. To create a custom inspector you will need to place an editor script in an Editor folder in your project but we will go through that later

Creating the MyButton class

First, let’s create the script for our custom button.

MyButton.cs inheritance from Button

If we attach this script to a gameobject you will see that you have all the normal controls for a button, but our new Overlay field does not show! Well as we just found out we need to create a custom inspector so we can tell Unity how to display the button. If you want to learn about Editor Scripting in general I can highly recommend this tutorial: https://learn.unity.com/tutorial/editor-scripting

Creating the custom inspector

The script for the custom inspector shall not be attached to a gameobject but there is another requirement and that is that the script is located inside any Editor folder. If you don’t have an Editor folder in your project, simply create one and create a new script called. “MyButtonEditor.cs” and put it inside that folder.

Now open up the script and let’s get to it.

Since we want to show content for a button an easy way to quickly get setup is that instead of just letting our class inherit from Editor, we can inherit directly from “ButtonEditor”. Thus you must replace Monobehaviour with ButtonEditor.

The method we want to override is ” OnInspectorGUI()” and inside the method we will explain the GUI drawer how to show a MyButton component in the inspector.

Since we only have one extra component, the “Overlay” it’s rather simple. After we have told the drawer how to show Overlay we will call the base method of the class to show the rest of the button components.

MyButtonEditor.cs

Now you will see the field is available in the inspector:

Congratulations!

You now know the basics about adding extra fields to already existing UI components in Unity. Thanks for reading I hope you will stop by at a later date 🙂