Does menuCommand.userdata actually do anything?

I’ve search the entire Unity forums, Answer boards, and stack overflow. A google search for “unity menuCommand.userdata” results in the scripting reference (which is useless), and 1 question on stack overflow about it, but the only told the one asking that they didn’t need to use “menuCommand.userdata” because, for their specific case, menuCommand.context, had everything they needed.

If there isn’t (and there isn’t, as far as I can tell) a way to pass a single integer flag to a menuitem function via userdata, then why does it exist? And furthermore, if that’s the case, I’d like to suggest that a named paramter be added to the MenuItemAttribute, so that an integer can be passed; this would open up a world of possibilities, and greatly simplify code, where, instead of needing to write a full method for each menu command (greatly annoying when you’re creating a set of options, e.g. an option to enable and an option to disable something), you could write one method, and set two two attributes, with different userData values.

[MenuItem("Assets/Options/Enabled")]
public static void EnableOptions(MenuCommand menuCommand){
/* Code */
}
[MenuItem("Assets/Options/Disabled")]
public static void DisableOptions(MenuCommand menuCommand){
/* Code */
}

could be greatly simplified and more organized into:

[MenuItem("Assets/Options/Enabled", userData = 1)]
[MenuItem("Assets/Options/Disabled", userData = 2)]
public static void EnableOptions(MenuCommand menuCommand){
/* Code */
}

The userData field isn’t added to your method when you define a menu item (using the MenuItem attribute).

You can use it manually from editor code by creating a MenuCommand and manually invoking a menu item to be displayed, for example - this is taken from Unity’s built in TerrainInspector class:

public void MenuButton(GUIContent title, string menuName, int userData)
{
    GUIContent content = new GUIContent(title.text, styles.settingsIcon, title.tooltip);
    Rect position = GUILayoutUtility.GetRect(content, styles.largeSquare);
   
    if (GUI.Button(position, content, styles.largeSquare))
    {
        MenuCommand command = new MenuCommand(this.m_Terrain, userData);
        EditorUtility.DisplayPopupMenu(new Rect(position.x, position.y, 0f, 0f), menuName, command);
    }
}

Note how a MenuCommand is constructed and then a popup menu is manually shown, passing in the command as an argument.

1 Like