Unity UIElements — menu

In this tutorial we will look at how the new UIElements can be used to create a Unity Editor window which has a menu list on the left hand side and display content for the selected menu entry on the right-hand side.

Image for post
Image for post

The first step is to define the editor window. If you work with editor side code a lot then this is very familiar to you. We will add a new main menu entry which will open the editor window.

Next we need to load the style sheet(s) and define the window layout and content. This is done in the OnEnable method which is called when the Window is enabled (opened for the 1st time). You might have seen UXML templates but in this case we will be doing everything in the C# code. Only the styles are defined externally.

The style sheet is saved in Assets\Editor\Resources\uie. Because the Resources folder is inside a folder named Editor these resources will not be part of a final build (your game executable). We only use these in the editor so that is preferred. It also allows us to manage the resources in a manner which does not care if the root folder locations changes, like loading with AssetDatabase.LoadAssetAtPath(...) would.

A menu is created and then the right-hand panel content area. The active menu item’s content will be added to this right-hand panel when a menu item is selected. Of course the previously visible content will be removed first if there is any.

To support the idea of menu entries that has content to display there is the GameEdContent type. This is a base class for editor content to be created. In the example I’ve create GameEd_Settings and GameEd_Characters types. These will be added to the menu, a ListView. You can define any number of these to be added.

The MakeMenu() method is where the menu is created. First you see the list of menu entries (game editors) to be added to the window, are made.

menuEntries = new List<GameEdContent>()
{
new GameEd_Settings(),
new GameEd_Characters(),
};
ListView menu = new ListView(menuEntries, 20, makeItem, bindItem);

This list is then provided to the ListView constructor. The 2nd parameter is the height of entries. The 3rd is a delegate to be called when a new item must be added to the list and should return a VidualElement. In this case we will create a TextElement. The 4th is used to set data related to a specific entry, in this case we update the text/label shown by the TextElement (menu entry).

The menu.onSelectionChanged will be called when a menu item is selected. So that is when we will respond and change what is shown in the right-hand panel.

The rest of the code should be pretty self explanatory but feel free to ask if something is not clear.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store