Good afternoon all,
I am trying to come up with a way to create a contextual menu for the editor’s scene view. I’ve figured out how to get it to register a right click and show a generic menu. The problem I’m having is that after I select a menu option, the scene view cursor becomes locked on the view movement tool you normally get when you right click. I can’t get it to switch back to the cursor in the scene view unless I start and stop playback. It appears that he scene view is being lock up by something in the Generic Menu. I’ve tried it without the menu and everything works fine, so I know it’s something about menu.ShowAsContext() that’s doing it.
I’ve included my code below; any help would be appreciated.
using System;
using UnityEditor;
using UnityEngine;
namespace iae
{
[InitializeOnLoad]
public class SceneViewInputHandler
{
#region Variables
//Has the mouse button been clicked?
private static bool isClicked = false;
//How long has the mouse button been held down?
private static float clickTime = 0f;
#endregion
static SceneViewInputHandler ()
{
//Add this class's OnScene method to the standard sceneview method
//so that it is always able to be referenced.
SceneView.onSceneGUIDelegate += OnScene;
}
static void OnScene(SceneView sceneView){
//Event handler
Event evt = Event.current;
//Check to see if we've right clicked
if(evt.isMouse && evt.type == EventType.MouseDown &&
evt.button == 1 && !isClicked){
//If all the conditions are met, the user has clicked
//the right mouse button
isClicked = true;
clickTime = 0f;
}
//Track the amount of time the mouse button is held down, if it
//exceeds a certain amount of time, assume the user wasn't right
//clicking and cancel
if(isClicked){
if(checkRightClick(Time.deltaTime, evt)){
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("Menu Item 1"), false, Callback, "Item 1");
menu.ShowAsContext();
evt.Use();
}
}
}
//Check to see if we've right clicked.
private static bool checkRightClick(float dT, Event evt){
clickTime += dT;
//If we exceed a certain amount of time, cancel the click checl
if(clickTime * 1000 >= 0.6f){
clickTime = 0f;
isClicked = false;
return false;
}
//If we've not exceeded the alloted time and the user released the
//button then we'll treat is as a mouse click
if(evt.isMouse && evt.type == EventType.mouseUp && evt.button == 1){
clickTime = 0f;
isClicked = false;
return true;
}
return false;
}
//Debug callback function
public static void Callback(object obj){
Debug.Log("Selection: " + obj);
}
}
}
A few notes:
I’ve tried it with and without evt.Use(); and I’ve tried moving evt.Use() to the Callback function. Neither of these helped.
If I hold the mouse button down longer than the allotted amount it will continue to operate fine once the mouse button is let up.
It has to be something with actually showing the generic menu because removing line 45 (menu.ShowAsContext()) fixes the locking problem.