As I mentioned before, for those who only want to use the editor, as soon as the Asset is available in the Unity Asset Store, you will be able to download it for free and use it.
This is the second part of a series of posts about a small tile editor I’m creating for Unity. If you haven’t read the first part yet, you can check it out here.
The whole explanation is divided in the following parts:
- Editor Window Creation
- Saving Status
- Menus
- Game Objects Actions: Create, Delete, Edit
- Layers
- Grid
- Snapping
- Transformations
- Snapping: Extended
This week we are going to cover point number 3: menus.
Menus
This section includes the concept of game object menu, which is an abstraction of a group of game objects (represented by prefabs) that are loaded inside a menu for the user to dynamically create instances of them in the editor.
As you can see in the picture above, this section was called “Game Objects” and represents a list of menus used to add new prefabs to the editor. It’s possible to add different menus, each one with a set of prefabs to add to the scene, it’s also possible to customize the menu a little to better organize the elements inside of it and remove it if necessary.
In the previous post, we created the main class file for out extension “LevelCreatorEditor”, which handles how the menus are created, all the operations for each menu and general operations as well. As we mentioned before, all the menus are rendered inside the method “OnGUI” and for this new section we added the “BuildMenuObjects” method.
List menus;
EditorObjectsMenu objMenu;
void OnGUI()
{
if (menus == null)
menus = new List();
//Header
BuildMenuHeader();
//Objects
BuildMenuObjects();
}
void BuildMenuObjects()
{
int curSel;
List removedMenus;
//If the group is empty, we disable this section
EditorGUI.BeginDisabledGroup(layers.Count <= 0);
//You can change the label if you want
GUILayout.Label("GAME OBJECTS", EditorStyles.boldLabel);
//Add menu button
if (GUILayout.Button("Add Menu"))
menus.Add(new EditorObjectsMenu());
removedMenus = new List();
//GUILayout.BeginVertical();
gameobjectsScrollPos = GUILayout.BeginScrollView(gameobjectsScrollPos, false, true);
//Menus
foreach (EditorObjectsMenu m in menus)
{
//Title
GUILayout.Label("Menu: " + m.folder, EditorStyles.boldLabel);
//Columns
m.columns = EditorGUILayout.IntField("Columns", m.columns);
//Folder's location
EditorGUILayout.BeginHorizontal();
m.folder = EditorGUILayout.TextField("Folder Name", m.folder);
if (GUILayout.Button("Load"))
m.LoadPrefabs();
EditorGUILayout.EndHorizontal();
//Load elements
if (m.tiles != null && m.tiles.Length >= 0 && m.columns >= 0)
{
curSel = GUILayout.SelectionGrid(m.selGridInt, m.tiles, m.columns, GUILayout.Width(position.width - 20),GUILayout.Height(100));
if (curSel != m.selGridInt)
{
m.selGridInt = curSel;
objMenu = m;
DeactivateMenus();
}
}
//Remove menu
if (GUILayout.Button("Remove"))
removedMenus.Add(m);
}
GUILayout.EndScrollView();
EditorGUI.EndDisabledGroup();
//Clean menus
foreach (EditorObjectsMenu m in removedMenus)
menus.Remove(m);
}
void DeactivateMenus()
{
foreach (EditorObjectsMenu m in menus)
{
if (objMenu == null)
m.selGridInt = -1;
else
{
if (objMenu != m)
m.selGridInt = -1;
}
}
}
Menus are logically represented using a List of “EditorObjectsMenu” which is a new class that has handles all the functionality inside a menu: loading new prefabs and converting them into usable icons, serializing the data to store changes for future use, etc.
public class EditorObjectsMenu
{
//Default folder that appears in the folder field
public const string DEFAULT_FOLDER = "Tiles";
//This will change depending on the folder's name
public string name;
//Folder's name
public string folder;
//Selected element
public int selGridInt;
//To organize the elements graphically, number of columns
public int columns;
//Textures of each prefab (from SpriteRenderer)
public Texture[] tiles;
//Prefabs that represent game objects
public Object[] prefabs;
public EditorObjectsMenu()
{
selGridInt = -1;
name = DEFAULT_FOLDER;
folder = DEFAULT_FOLDER;
columns = 3;
}
/// Load all the prefabs in folder "folder"
public void LoadPrefabs()
{
GameObject obj;
prefabs = Resources.LoadAll(folder, typeof(Object));
tiles = new Texture[prefabs.Length];
for (int i = 0; i < prefabs.Length; i++)
{
obj = ((GameObject)prefabs[i]);
if (obj.GetComponent().sprite == null)
{
for (int j = 0; j < obj.transform.childCount; j++)
{
if (obj.transform.GetChild(j).GetComponent().sprite != null)
{
tiles[i] = obj.transform.GetChild(j).GetComponent().sprite.texture;
break;
}
}
}
else
tiles[i] = obj.GetComponent().sprite.texture;
}
}
/// Get the the selected element
public Object GetCurrentSelection()
{
Object sel;
sel = null;
if (selGridInt != -1)
sel = prefabs[selGridInt];
return sel;
}
/// Transform the object's parameters into a string (to save the state of the object)
public string Serialize()
{
return name + "," + folder + "," + selGridInt + "," + columns;
}
/// Takes a serialized string and loads all the parameters of the object
public void Deserialize(string data)
{
string[] attributes = data.Split(',');
name = attributes[0];
folder = attributes[1];
selGridInt = int.Parse(attributes[2]);
columns = int.Parse(attributes[3]);
}
}
The EditorObjectsMenu class has properties such as: name, folder, selGridInt, columns, tiles and prefabs. Name and folder are the same but one is used to display the id in the GUI and the other to decide where should the prefabs be loaded from; selGridInt represents the selected element (prefab); columns, is there to customize the number of columns each menu displays; tiles is an array of textures that are mapped to the prefabs and help to display the prefabs buttons inside the menu.
LoadPredabs takes the folder path (which should be inside the physical folder “Resources” and loads all the prefabs inside that path. This data is stored in the textures and prefabs arrays to be displayed in the menu.
GetCurrentSelection just returns which of the current element was selcted by the user and with that we can create instances of that object in the editor.
Finally Serialize and Deserialize were created to easily convert the data to strings and store it as we explained in the previous post.
Going back to the previous method “BuildMenuObjects” now that the EditorsObjectMenu is defined, we can see that the new attribute called “menus” is a list of elements of EditorsObjectMenu class. With this variable we represent logically all the menus that are rendered in the GUI.
Adding Menus
We create a new button inside the GUI called “Add Menu”, the code can be seen in the “BuildMenuObjects” function above:
if (GUILayout.Button("Add Menu"))
menus.Add(new EditorObjectsMenu());
Here we just create a new instance of the class and add it to the menu list and it automatically will render the information and inputs for that new menu.
Rendering Menus
All the menus are rendered inside a foreach instruction that handles each input of the menu separately:
foreach (EditorObjectsMenu m in menus)
{
//Title
GUILayout.Label("Menu: " + m.folder, EditorStyles.boldLabel);
//m.name = EditorGUILayout.TextField("Title", m.name);
//Columns
m.columns = EditorGUILayout.IntField("Columns", m.columns);
//Folder's location
EditorGUILayout.BeginHorizontal();
m.folder = EditorGUILayout.TextField("Folder Name", m.folder);
if (GUILayout.Button("Load"))
m.LoadPrefabs();
EditorGUILayout.EndHorizontal();
//Load elements
if (m.tiles != null && m.tiles.Length >= 0 && m.columns >= 0)
{
curSel = GUILayout.SelectionGrid(m.selGridInt, m.tiles, m.columns, GUILayout.Width(position.width - 20),GUILayout.Height(100));
if (curSel != m.selGridInt)
{
m.selGridInt = curSel;
objMenu = m;
cursorState = CursorState.Add;
DeactivateMenus();
}
}
//Remove menu
if (GUILayout.Button("Remove"))
removedMenus.Add(m);
}
Here basically we handle basic information for the menu: name, location. There is also a field called “Folder Name” that specifies the path of the data. After the user writes the name of thr folder down, clicks “Load” and all the prefabs will be loaded automatically inside the menu, using the SpriteRenderer’s texture as icon image. In case that the SpriteRenderer for a prefab is empty, the algorithm automatically searches inside the children of this prefab and takes the first non null texture and use it.
Removing Menus
In the previous code we can see that a “removedMenus” list was created in additio to the general menus list. This is emptied everytime before the cycle for rendering menus starts so if the user removes a menu using the remove button, it will add it to this new list and delete all menus from the main list after the cycle finishes. This is done to prevent collection changes inside the cycle.
Deactivate Menus
Finally, this method verifies if any of the elements on any menu was selected and in case it was not selected it deactivates the whole menu. This was used to have only one element selected at the time, if we do not do this, then two different menus could have one element selected each and we don’t want that when creating new instances.
With the menu deactivation I want to close this post, I’ll continue explaining the rest of the code in upcoming articles. If you have questions, leave in them in the comments.
Leave a Reply
You must be logged in to post a comment.