Search Unity

Question Do ContextualMenus only work during runtime?

Discussion in 'UI Toolkit' started by VoodooDetective, Sep 13, 2022.

  1. VoodooDetective

    VoodooDetective

    Joined:
    Oct 11, 2019
    Posts:
    239
    I've been unable to get context menus to show up. Here's my code:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UIElements;
    3.  
    4. public class Test : MonoBehaviour
    5. {
    6.     private UIDocument _uiDocument;
    7.     private VisualElement _redSquare;
    8.  
    9.     private void OnEnable()
    10.     {
    11.         _uiDocument = GetComponent<UIDocument>();
    12.         _redSquare = _uiDocument.rootVisualElement.Q<VisualElement>(name: "test");
    13.         _redSquare.focusable = true;
    14.         _redSquare.pickingMode = PickingMode.Position;
    15.         _redSquare.AddManipulator(new ContextualMenuManipulator(HandleContextMenuEvent));
    16.     }
    17.  
    18.     private void HandleContextMenuEvent(ContextualMenuPopulateEvent contextMenuEvent)
    19.     {
    20.         contextMenuEvent.menu.AppendAction($"TESTING", HandleTestingClick, DropdownMenuAction.AlwaysEnabled);
    21.     }
    22.  
    23.     private void HandleTestingClick(DropdownMenuAction dropdownMenuAction)
    24.     {
    25.         Debug.Log("TEST");
    26.     }
    27. }
    28.  
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,938
    Show up when? On a monobehaviour whilst outside of playmode?
     
  3. VoodooDetective

    VoodooDetective

    Joined:
    Oct 11, 2019
    Posts:
    239
    Ah, so sorry! I meant do they work for runtime UI during playmode or only as an editor UI. For anyone else who's wondering: they only work for editor UI
    .
     
  4. VoodooDetective

    VoodooDetective

    Joined:
    Oct 11, 2019
    Posts:
    239
    I wrote a custom contextual menu implementation using UI Toolkit that supports runtime usage. Please feel free to check it out.
     
    Last edited: Sep 19, 2022
    yoso-ul likes this.
  5. yoso-ul

    yoso-ul

    Joined:
    Mar 28, 2023
    Posts:
    2
    thx, for this work =)