- Home /
Tracking the Mouse Position in the Editor
Debug.Log(Input.mousePosition);
does not work inside the editor. Is there a way to track the mouse in the Editor? Specifically, I'm trying to detect a mouse hit on an object in the scene, while in the Editor and I need the mouse position to do this. Any insight would be helpful. Thanks.
Answer by Jesse Anders · Sep 02, 2010 at 05:26 AM
The 'Input' class is not active in editor mode. Based on the examples I've seen, accessing of events in editor scripts is typically done by accessing 'Event.current' directly.
Also, if you're going to be doing picking in editor mode, be sure to use HandleUtility.GUIPointToWorldRay() to generate the pick ray, as using ScreenPointToRay() with the scene view camera doesn't produce the correct results (or at least that's what I've found).
Been messing around with a custom terrain editor and this is the only solution I've found for this, thank you so much! I've been looking for half an hour!!
Thank you so much for this. I have been trying to figure this out for over 2hours now. HandleUtility.GUIPointToWorldRay(Event.current.mousePosition) works like a charm!
Answer by Darkgaze · Aug 18, 2020 at 03:14 PM
I add some more info to the previous correct answer:
You can attach to the event:
SceneView.onSceneGUIDelegate += OnSceneGUI;
Then write your own function:
private void OnSceneGUI(SceneView sceneView)
Inside, take the mousePos using Event.current, instead of Input, which is disabled in Editor mode.
Vector3 mousePosition = Event.current.mousePosition;
Ray ray = HandleUtility.GUIPointToWorldRay(mousePosition);
Others say using ScreenPointToRay instead. This happens in other scenarios. In that case you have to flip Y.
Vector3 mousePosition = Event.current.mousePosition;
mousePosition.y = sceneView.camera.pixelHeight - mousePosition.y; // Flip y
Ray ray = sceneView.camera.ScreenPointToRay(mousePosition);
That's actually a necessary update since a lot of those things you've mentioned didn't even exists when this question was asked / answered. Though be careful with na$$anonymous$$g your method OnSceneGUI because inside a custom editor (class derived from UnityEditor.Editor) this is already a callback that is called by Unity.