Search Unity

GenericMenu used as context, inside a MenuItem ?

Discussion in 'Immediate Mode GUI (IMGUI)' started by smaraux, Jun 2, 2015.

  1. smaraux

    smaraux

    Joined:
    May 28, 2015
    Posts:
    10
    Hello ,

    I would like to add a contextual menu at mouse position, when the user clicks on a MenuItem. I tried this (and many more) but can't manage to do what I want. Action list is filled dynamicaly, thus I cannot declare several submenus to MenuItem.

    [MenuItem("Assets/DoSomething")]
    static void DoSomething(MenuCommand menuCommand)
    {
    GenericMenu menu = new GenericMenu();
    menu.AddItem(new GUIContent("Action1"), true, SomeClass.ActionCallback, "Action1");
    menu.AddItem(new GUIContent("Action2"), false, SomeClass.ActionCallback, "Action2");
    menu.ShowAsContext();
    }

    Is there a way to do it ?
    I also tried with EditorWindow, but ended up with a window (dockable editor) which is not what I want
     
    noio likes this.
  2. noio

    noio

    Joined:
    Dec 17, 2013
    Posts:
    232
    I've run into the same issue. It looks like it is impossible to show a GenericMenu() from inside a [MenuItem].

    However, that seems like the only way to summon a dynamic list of options!


    Hard to imagine nobody else ran into this?
     
  3. noio

    noio

    Joined:
    Dec 17, 2013
    Posts:
    232
    Hahaha. Always great when you search for an answer on Google, and end up with your own post concluding that it is not possible.
     
  4. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,330
  5. noio

    noio

    Joined:
    Dec 17, 2013
    Posts:
    232
    I did. That also doesn't work, actually.

    I think the menu has to be shown inside a GUI event.
     
  6. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,330
    If that is the case it's a tougher nut to crack.

    To my knowledge there is no easy and reliable way to get OnGUI callbacks in the editor without creating an EditorWindow. There are things like SceneView.duringSceneGui and EditorApplication.hierarchyWindowItemOnGUI, but those won't work unless the window in question is open in the editor. An ugly hack of a solution would be to create a temporary off-screen EditorWindow and leverage its OnGUI function to open the menu.

    Or you could also create your own PopupWindow, that would probably work.
     
  7. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,330
    Also, I seem to have a hazy recollection that GenericMenu.ShowAsContext can not be called outside of mouse click events, but that GenericMenu.DropDown can. Not sure if GenericMenu.DropDown still requires OnGUI or works when called from a menu item though.
     
    noio likes this.