Learn Unity Editor Scripting: Editor Windows (Part 5)
In this post we will learn how to create our custom editor windows in Unity. console, project view and asset store are samples of editor windows.
This article is part of a series in which I explain all the techniques for extending the Unity Editor. See the overview post here.
Prerequisite: You need to know C# programming and be familiar with Unity Editor to benefit most from this post. You also need to know either IMGUI or UIElements for creating GUIs in Editor. In this post I will use IMGUI.
There is an accompanying Unity project. I highly recommend downloading it and trying the topics as you read them here. Seeing the examples in action makes them stick to your brain.
For instructions on how to get started with the project, see the overview post.
Without further ado, let’s jump in!
Creating an Editor Window
Create a new file named MyEditorWindow.cs under the Editor folder.
Code explanation:
- Our class needs to extend the
EditorWindow
class. - We are using the
MenuItem
attribute which we learnt about in the previous post to show a menu item to toggle our window. - Line 15,
myWindow.titleContent
sets the title of our window. By default Unity uses the fully qualified name of the class which in our case is NoSuchStudio.ExtendingEditor.Editor.MyEditorWindow. Here we change it to “My Window”.
My Window
menu item will show our window if it is hidden, or hide it if it is already being shown.GetWindow<T>
gets an editor window of type T if one already exists. It will create and show a new one if one doesn’t already exist.EditorWindow.Close()
closes an editor window.OnGUI
is the message similar to the one inMonoBehaviour
. We define our own GUI in that method.
For now our Editor window doesn’t show any useful GUI, but otherwise can be moved around, resized and docked like any other editor window.
Adding GUI to Our Window
We can use either IMGUI or UIElements to create our UI in an Editor Window. Let’s stick with IMGUI which we have used so far in this series.
Change the code in OnGUI
method to the following in MyEditorWindow.cs.
You should be able to understand what’s going on. I’ll make a post on IMGUI later and put a link here.
In any case, our window now shows some basic stats about the level like the number of targets, total score and the surface area of the arena.
Conclusion
In this post we learnt how to create an Editor Window in Unity and show / hide it.
If you have any questions and suggestions about this post, feel free to leave a comment.
If you find this tutorial useful, please support me on Patreon. It takes a good amount of time to write these tutorials and your support will keep me going. Thank you!
In the next post, we will see how to interact with the Scene view and show our custom gizmos and UI there. (ETA Nov 18th 2020).