I am trying to write a custome EditorWindow to handle adding a variety of objects and connected structures to my game environment. However, I have run into a problem where I can not figure out how to detect when and where the user clicks in the scene view when my editor window is active.
Is there anyway to get mouse events from an EditorWindow?
I was able to get the mouse events from the scene window by using the mostly undocumented SceneView class. In the OnEnable function I had to register a delegate with SceneView so I believe it is being called with each onSceneGUI from the Editor. This allows the EditorWindow to be called on scene events.
void OnEnable()
{
SceneView.onSceneGUIDelegate += SceneGUI;
}
void SceneGUI(SceneView sceneView)
{
// This will have scene events including mouse down on scenes objects
Event cur = Event.current;
}
here are two scripts to solve this:
-
it is auto initialized when unity editor starts (even when you don’t select the game object of the script)
-
it requires a game object in the scene tagged with “EditorMousePos”
-
that game object must have the script EdotorMousePos.cs
public class EditorMousePos:MonoBehaviour
{
public Vector3 editorMousePos;
public Vector3 editorMouseWorldPos;
}
[InitializeOnLoad]
public class EditorMousePosEditor
{
static EditorMousePosEditor(){
SceneView.onSceneGUIDelegate += SceneGUI;
Debug.Log(“constructor created”);
}
static void SceneGUI(SceneView sceneView)
{
// This will have scene events including mouse down on scenes objects
Event cur = Event.current;
Vector3 mousePos=(Vector3)cur.mousePosition;
mousePos.y = Camera.current.pixelHeight - mousePos.y;
Vector3 worldPos=sceneView.camera.ScreenToWorldPoint(mousePos);
EditorMousePos editorMoseuPos=GameObject.FindGameObjectWithTag("EditorMousePos").GetComponent<EditorMousePos>();
editorMoseuPos.editorMousePos=mousePos;
editorMoseuPos.editorMouseWorldPos=worldPos;
}
}
Get the current editor event within Editor.OnSceneGUI() or EditorWindow.OnGUI(). You can get the mouse position from the event directly, or use HandleUtility.GUIPointToWorldRay(Vector2) to check for collision with scene objects.