Listen for key up/down in editor mode?

Is there any way to listen for a key press in editor mode? I found some posts that said you could use OnSceneGUI to listen for events, but those don’t work. You don’t get key events, just mouse move and repaint. They also require extending Editor which is not ideal.

Event is probably what you’re looking for.
To read a key-press:

//Returns true if any key was pressed.
if(Event.current.isKey)
{
   //The key that was pressed.
   KeyCode key = Event.current.KeyCode;
}

Additionally, if you need to detect if the Shift or Ctrl keys were pressed, there is a shortcut for those:

if(Event.current.control)
{
   //Ctrl key pressed.
}

if(Event.current.shift)
{
   //Shift key pressed.
}

You may not need to extend the editor, since any pre-existing OnGUI functionality will populate the Event.current reference, but if you are making a custom editor, you will have to use some kind of OnGUI-type method to listen for Events (OnGUI, OnSceneGUI, OnInspectorGUI, etc.). There’s no way around it.

1 Like

When I tried using Event, like I mentioned in my 1st post, I didn’t get any key events. Is there some special setup I need to use?

If I make a monobehavior like this, I get no key events.

[ExecuteInEditMode]
public class DragClone : MonoBehaviour
{
    private void OnGUI()
    {
        Debug.Log(Event.current);
    }
}

If I extend Editor instead and use OnSceneGUI, I also get no key events. It’s mostly just repaint, layout, and mouse move events.

Old post but unanswered.

This is how I do it:

using UnityEngine;
using UnityEditor;

public class YourClassName
{
        [UnityEditor.Callbacks.DidReloadScripts]
        private static void ScriptsHasBeenReloaded()
        {
            SceneView.duringSceneGui += DuringSceneGui;
        }

        private static void DuringSceneGui(SceneView sceneView)
        {
           Event e = Event.current;
         
           if (e.type == EventType.KeyUp)
           {
              //Do Something
           }

           if (e.type == EventType.KeyDown)
           {
              //Do Something
           }

           //Right mouse button
           if (e.type == EventType.MouseDown && Event.current.button == 0)
           {
       //Do Something
      }
   }
}
  • You need UnityEngine for events to work.
  • You need UnityEditor for SceneView.
  • Use any callback as [UnityEditor.Callbacks.DidReloadScripts].
  • The function (ScriptsHasBeenReloaded()) has to be static.
  • Subscribe with any function to SceneView.duringSceneGui. That function also needs to be static.
7 Likes