10. Extending Context Menus

  10. Extending Power Inspector No Comments

You can add new context menu items to Unity Object targets just like you always have using the MenuItemAttribute.

If you would like to add new items to the context menus of other drawers, you can do so by subscribing to the OnMenuOpening callback in the ContextMenuUtility class.
This gets called after the context menu of an element inside the inspector view has been built, but before it is displayed to the user, thus making it possible for you to slip in your own menu items before this happens.

Note that the callback is also called when context menus open for elements besides drawers, such as toolbar items, and thus you should always check that menuSubject is not null before accessing any of its data.

Example

public class ExtendingMenuExample : MonoBehaviour
{
    void OnEnable()
    {
        // Subscribe to the menu opening callback when this MonoBehaviour becomes active.
        ContextMenuUtility.OnMenuOpening += OnMenuOpening;
    }

    void OnMenuOpening(Menu menu, IInspector inspector, IDrawer menuSubject)
    {
        // Only add items to context menu if it is opening for a drawer.
        If(menuSubject != null)
        {
            // Add a separator line, but only if menu is not empty and last item is not a separator
            Menu.AddSeparatorIfNotRedundant();

            // Add a new item to the menu that allows copying the name of the drawer to the clipboard.
            menu.Add("Copy Name", ()=>Clipboard.Copy(menuSubject.Name));
        }
    }

    void OnDisable()
    {
        // Unsubscribe from the menu opening callback when this MonoBehaviour is no longer active.
        InspectorUtility.OnMenuOpening -= OnMenuOpening;
    }
}

 

Note: The MenuIsOpening callback does not get called when context menus are opened from inside custom editors. You can use the EditorApplication.contextualPropertyMenu callback in those cases.