- Home /
Sort a GenericMenu alphabetically.
Hi, I have a list of strings representing their path in a GenericMenu. How could I go about sorting them so that the root folders are sorted as well as their contents?
For example
Utility/Wait for Time
Control/On Level Load
Control/If
becomes
Control/If
Control/On Level Load
Utility/Wait for Time
Does GenericMenu support this kind of functionality or will I have to split the list by '/'s and then sort through them? Because that sounds like a bit of a pain to me. Thank you!
Answer by Bunny83 · Nov 05, 2017 at 09:34 PM
The items in a generic menu always appear in the order you added them. Keep in mind that a menu item can also be a seperator, sub menu or disabled item. You just have to add them in the order you want. You haven't really said how you build your menu. Where do your menu items come from? Your question is a bit abstract and can't really be answered in it's current state.
The GenericMenu class really is nothing more than this. It's just a wrapping class around this built-in internal method "EditorUtility.DisplayCustomMenuWithSeparators". You have to sort the items yourself. If you want to provide categories it would be the easiest way to actually represent them with your own classes.
I've quickly created those helper classes. They allow you to create a GenericMenu in a more generic way, actually using submenus. The built-in Sort method will sort all items up to the next seperator. So a single menu / submenu is split into sections at seperators. This allows easy sorting of a single section.
Here's an example usage:
var m = new B83.UnityEditorExt.Menu();
m.AddItem("XXX", () => Debug.Log("MainMenuItem1"));
m.AddItem("AAA", () => Debug.Log("MainMenuItem2"));
m.AddSeperator();
var m2 = m.AddSubMenu("XSub");
m2.AddItem("YYY", () => Debug.Log("XSub / YYY"));
m2.AddItem("BBB", () => Debug.Log("XSub / BBB"));
var m3 = m.AddSubMenu("ASub");
m3.AddItem("ZZZ", () => Debug.Log("ASub / ZZZ"));
m3.AddItem("CCC", () => Debug.Log("ASub / CCC"));
m.Sort();
GenericMenu menu = m.CreateMenu();
menu.ShowAsContext();
So a Menu simply hold a direct list of menu items. This can be a normal "TextItem" or another "Menu" for submenus. Finally you can call "Sort" on the top most menu to sort all sections recursively.
Your answer
![](https://koobas.hobune.stream/wayback/20220612142449im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Menu, Game mode Array String to change settings? 1 Answer
Initialising List array for use in a custom Editor 1 Answer
Menu Selection using 360 Controller 0 Answers