Hey guys,
Does anybody know how do I do Right-Click stuff in a Custom Editor?
Like, for instance, when you right-click on an array item (default editor), it will show Duplicate Array Elem and Delete Array Elem. I would like to do that too for my custom list, but I’m not too sure how…
Unity’s editor makes use of an IMGUI system, in other words, you procedurally generate the UI based on events that occur.
As a result, you need to be aware of polling. This idea revolves around waiting for a valid event to reach you, then doing a thing based on that event.
In the right click case, you’ll be after a context click.
The Event class provides you with a way to see which event is currently being processed. If the current event is a context click, do something.
Something along these lines:
Rect clickArea = EditorGUILayout.GetControlRect();
Event current = Event.current;
if(clickArea.Contains(current.mousePosition) && current.type == EventType.ContextClick)
{
//Do a thing, in this case a drop down menu
GenericMenu menu = new GenericMenu();
menu.AddDisabledItem(new GUIContent("I clicked on a thing"));
menu.AddItem(new GUIContent("Do a thing"), false, YourCallback);
menu.ShowAsContext();
current.Use();
}
void YourCallback()
{
Debug.Log("Hi there");
}
A small breakdown.
First we have to grab some space, we need to know what classifies as a valid click. This should only occur when the click occurs over the clickArea, otherwise we can ignore it because something else may want it.
Then we peak at the current event, and do the necessary checks. In this case, we only want to process the click if it’s inside the clickArea and the type is a ContextClick, otherwise ignore it.
If we are inside the click area and the type is correct, then we do a thing. In this case we display a generic menu. Don’t forget to use the event if you have to. This will prevent anything else from responding to the context click. If you don’t use it, another control may use it and cause unexpected behaviour. Only use events if your control is valid, in this case, if you context click inside the area.
Some reading:
Generic menu, good example of right clicking: Unity - Scripting API: GenericMenu
Event: Unity - Scripting API: Event
EditorGUILayout.GetControlRect: Unity - Scripting API: EditorGUILayout.GetControlRect
Hopefully this’ll help.