Search Unity

Contextual Menu event has wrong mouse position

Discussion in 'UIElements' started by ilEtik, Sep 11, 2019.

  1. ilEtik

    ilEtik

    Joined:
    Jan 4, 2018
    Posts:
    3
    Hi, I'm currently working on Node-Based System with UIElements. At the moment I'm trying to make a menu like the one when you right click in the shadergraph view.
    For this i'm using the ContextualMenuManipulator wich I add to my nodeContainer and this works fine for me. Now I have a new EditorWindow for creating new nodes and this window works also fine. But when I open it during the ContextualMenu it sets its position to 0, but I want the position to be where the mouse is.
    It works when I just register a callback to my nodeContainer and I tried every type of mousePosition Vector2 in the ContextualMenuPopulateEvent.

    The code for adding the menu and events:

    Code (CSharp):
    1.         void SetEvents()
    2.         {
    3.             nodeContainer.AddManipulator(new ContextualMenuManipulator((evt) =>
    4.             {
    5.                 var mPos = evt.originalMousePosition;
    6.                 evt.menu.AppendAction("Add Node",
    7.                     (a) => OpenNodeMenu(evt),
    8.                     (a) => DropdownMenuAction.Status.Normal);
    9.             }));
    10.  
    11.             nodeContainer.RegisterCallback<MouseDownEvent>(OpenNodeMenu);
    12.         }
    13.  
    14.         void OpenNodeMenu(EventBase evt)
    15.         {
    16.             Debug.Log("Menu opend");
    17.             NodeCreatorMenu.Show(window, evt.originalMousePosition);
    18.         }
    19.  
    And the code in the EditorWindow that I want to open:
    Code (CSharp):
    1. public static void Show(EditorWindow host, Vector2 displayPosition)
    2.     {
    3.         var window = CreateInstance<NodeCreatorMenu>();
    4.         var position = GetPosition(host, displayPosition);
    5.         window.position = new Rect(position + host.position.position, s_DefaultSize);
    6.         window.ShowPopup();
    7.         window.Focus();
    8.     }
    9.  
    10.     private static Vector2 GetPosition(EditorWindow host, Vector2 displayPosition)
    11.     {
    12.         var x = displayPosition.x;
    13.         var y = displayPosition.y;
    14.  
    15.         if (x + s_DefaultSize.x >= host.position.size.x)
    16.             x -= s_DefaultSize.x;
    17.  
    18.         if (y + s_DefaultSize.y >= host.position.size.y)
    19.             y -= s_DefaultSize.y;
    20.  
    21.         return new Vector2(x, y);
    22.     }
    I used code from this thread: https://forum.unity.com/threads/dropdownmenu-with-right-click.592696/
     
  2. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    226