While developing games, I see many developers or teams will customize the editor of their owns corresponding to their demands on the project. For example, supposed someone is developing a game, in which PlayerPrefs data should be frequently checked and modified. In traditional way, we can only print out debug information or directly modify the PlayerPrefs file (Not recommended). By using editor extensions, we can now open a window from the toolbar, then check and modify the data inside the window. That’s so much convenient and efficient!
Reference tutorial: Editor Scripting
Customize Inspector
Customize inspector means we can modify the default inspector of any component, including the built-in ones and the custom ones.
Suppose we have a custom component named TestObject, which has two fields and a property.
- Health: Current health.
- Max Headth: Max health.
- HealthPercentage: Percentage of the current health to max.
1 | using UnityEngine; |
By default, because HealthPercentage is a property with public getter and private set, it will not be shown in the inspector. Then we can use editor extension to show that value.
1 | using UnityEngine; |
We create a new class inherited from Editor, and rewrite its OnInspectorGUI() function.
DrawDefaultInspector simply draws the default inspector view (here the view contains Health and MaxHealth).
Add Functional Buttons
Also we can bind function to a button in the inspector so that we can call our functions directly from the editor and improve our workflows.
1 | public class TestObject : MonoBehaviour { |
After that, a button will be shown in the inspector of TestObject, which allows us to increase the max health by one.
Menu Items
The Unity editor allows adding custom menus that look and behave like the built-in menus. If we want to add/extend a new menu to the top-level toolbar, we should write the corresponding static function and mark it with the MenuItem attribute.
1 | using UnityEngine; |
Customize Editor Windows
We can also create a new menu item binded with a custom window. For example, like what we said in the header of this article, we want to check and modify the PlayerPrefs data inside the inspector, just click a menu item from the toolbar, and do the manipulations in a window. That’t cooooooool.
We need to create a class inherited from EditorWindow and rewrite the OnGUI() function. Also we need to create a static function marked with the MenuItem attribute for the reason of menu item.
Here we give an example code implemented by Romejanic, which just do the job we need.
1 | using UnityEngine; |