Creating Custom Editor Window in Unity

When you become a pro you start customizing the product to your need. Unity experts generally have multiple custom features into their editor that helps in their workflow. To start with let’s try to build a custom window in our Unity Editor.

We will learn the following concepts in this tutorial

Note: Do not add any editor scripts to your Gameobjects

Creating an Empty Editor Window

Right click on the Project Window>Create>C# Script.

Unity Black Friday Deals

Let’s name it MyWindow.

Open MyWindow script in your code editor.

Add the namespace “using UnityEditor”. This is required for all editor scripts.

We need to drive the class from EditorWindow rather than MonoBehaviour.

using UnityEditor;
using UnityEngine;

public class MyWindow : EditorWindow
{
   void OnGUI()
   {
   }
}

Now you have created a new Window that is totally empty and no way to Open.

In order to enable Unity to open your window you need to add a public static function that calls the window.

Here is the code sample


public class MyWindow : EditorWindow
{
    public static void ShowWindow()
    {
        EditorWindow.GetWindow(typeof(MyWindow));
    }
   void OnGUI()
   {
   }
}

Creating a new Menu Item in Unity editor

Let’s create a new Menu item so that you can access your Window from the Unity Editor’s Menu.

This can be done with a simple line of code where you call the MenuItem function and pass your window path.

Let’s place out window under Windows menu.

[MenuItem("Window/My Window")]

Save your script and head back to your Unity Editor.

Now you should see a My Window menu item.

Window menu

Now if you click on My Window menu item, you should see an empty window with the title My Window

Populating your window items

Whatever you want to add in your window should go into the OnGUI function of your code.

Most of the UI elements will be inside the following three funcitons

  • GUILayout
  • EditorGUILayout
  • EditorGUI

For the sake of this tutorial, let’s add a Label, a Text field, a Boolean check box, a Slider and a Button.

Lable and Button will be under GUILayout. The rest of the components will be under EditorGUILayout.

Add the following script to your OnGUI function.

void OnGUI()
    {
        GUILayout.Label ("This is My Window", EditorStyles.boldLabel);
        myString = EditorGUILayout.TextField ("Text Field", myString);
        myBool = EditorGUILayout.Toggle ("Toggle", myBool);
        myFloat = EditorGUILayout.Slider ("Slider", myFloat, 0, 10);
        GUILayout.Button("My button");
    }

Your custom window should look like this

Final custom window

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.