- Home /
Is there a way to implement mouse events in the game view in edit mode?
I'm creating custom workflow tools in the Unity Editor and I'd like to intercept mouse events in the game view (not the scene view) to implement custom behaviors but am not having much luck. The most basic feature I want is to select an object clicked in the game view.
I've explored different approaches and I have a somewhat working script, but there are issues.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[ExecuteInEditMode()]
public class TestClick : MonoBehaviour
{
#if UNITY_EDITOR
public void OnGUI()
{
Event e = Event.current;
if (e == null) return;
Debug.Log("Event:"+ e);
if (e.button == 1) {
Debug.Log("Event:" + e.type +" pos:" + e.mousePosition + " camera:" + Camera.current.name + " button:" + e.button + " isMouse:" + e.isMouse);
GameObject picked = HandleUtility.PickGameObject(e.mousePosition, false);
if (picked == null) {
Debug.Log("Nothing picked");
}
else {
Debug.Log("picked:" + picked.name);
}
}
}
#endif
}
The first issue is that the only event types received are Repaint and Layout. For some reason OnGUI is not getting any other types of events, so even though I can detect e.button, e.isMouse is always false, making it impossible to handle the events properly.
Secondly, even though PickedGameObject is working in that returns the right object, I get these errors from it:
GUI Window tried to begin rendering while something else had not finished rendering! Either you have a recursive OnGUI rendering, or the previous OnGUI did not clean up properly.
Assertion failed on expression: 'device.IsInsideFrame()'
I tried putting these in a Handles.BeginGUI and EndGUI block, but makes no difference.
Is there a better way to intercept mouse events in the game view in edit mode? Not opposed to making an editor window, but I could not find a way to get any mouse events outside of the window.
Answer by sarahnorthway · Feb 23, 2021 at 07:11 PM
I learned here that calling EditorUtility.SetDirty during those Layout/Repaint events will cause mouse events to fire. Not sure why? I then use a raycast to find the object under the mouse in the Game window (requires colliders though).
#if UNITY_EDITOR
private void OnGUI() {
if (Event.current.type == EventType.Layout || Event.current.type == EventType.Repaint) {
UnityEditor.EditorUtility.SetDirty(this);
} else if (Event.current.type == EventType.MouseDown) {
DoMouseDown();
}
}
private void DoMouseDown() {
Vector2 mousePos = Event.current.mousePosition;
mousePos.y = Screen.height - mousePos.y;
Ray ray = Camera.main.ScreenPointToRay(mousePos);
bool raycastSuccess = Physics.Raycast(ray, out raycastHit, 1000);
if (!raycastSuccess) return;
Debug.Log("Clicked on " + raycastHit.collider + " at " + raycastHit.point);
}
#endif
(edit: found the unrelated bug that was messing with my Hierarchy view)