Unity3d MenuItem and Separators

Recently got a chance to work on some extensions in the Unity3D editor. On of the problem I've got is adding separators to the MenuItems. There seems to be no documents regarding this and searching over the Internet does help (Separator in custom Editor MenuItem) but there's no explanation over the code at all. So I did some simple experiments.

Adding Custom MenuItems

Adding custom MenuItems to the editor is easy. Just use the MenuItem decorator over any static method.

Official Document Here

[MenuItem("My Menu/Hello World")]
static void MenuHelloWorld() {
    Debug.Log("Hello World");
}   

Validate Function

There is also a optional validate function over the MenuItem to enable/disable it according to current states.

The second parameter of the MenuItem decorater is the validate function flag.

[MenuItem("My Menu/Hello World")]
static void MenuHelloWorld() {
    Debug.Log("Hello World");
}   

// validate the previous menu item 
[MenuItem("My Menu/Hello World", true)]
static bool ValidateMenuHelloWorld() {
    // return false if disabled
    return true;
}   

Priority and Separators

The third optional argument of the MenuItem decorator is the priority of the menu item. The priority controls the order of the menu items in the menu, and also its related to separators.

[MenuItem("My Menu/Hello World", false, 1)]
static void MenuHelloWorld() {
    Debug.Log("Hello World");
}   

// "Goodbye world" will below "Hello World"
[MenuItem("My Menu/Goodbye World", false, 2)]
static void MenuGoodbyeWorld() {
    Debug.Log("Goodbye World");
}

Add if you want a separator between any two menu items, just make sure the difference of the priority between them is larger than 11.

For example

[MenuItem("My Menu/Hello World", false, 1)]
static void MenuHelloWorld() {
    Debug.Log("Hello World");
}   

// "Goodbye world" will below "Hello World"
// And there will a separator between them!
[MenuItem("My Menu/Goodbye World", false, 12)]
static void MenuGoodbyeWorld() {
    Debug.Log("Goodbye World");
}

blog comments powered by Disqus