In my EditorWindow, I would like that whenever the user clicks a GUILayout.Button I know which of the alpha keyboard keys the user pressed while clicking the button.
I can’t make it work with:
private void OnGUI()
{
if (GUILayout.Button("Test"))
{
Event e = Event.current;
if (e.shift)
{
Debug.Log("This works!");
}
if (e.keyCode == KeyCode.Alpha1)
{
Debug.Log("This doesn't work, Alpha1 is not detected when triggering the button");
}
}
}
OnGUI gets called separately for each UI event type, such as KeyDown and KeyUp. Event.keyCode is only valid for specific event types, such as KeyDown and KeyUp. In OnGUI, you’re going to have to check the Event.current.type. If it’s KeyDown, record that the key (e.g., Alpha1) is pressed down. If it’s KeyUp, record that the key is up.
I tried what you suggested, it does not work when clicking on a button. Maybe I misunderstood something?
private void OnGUI()
{
var e = Event.current;
if (GUILayout.Button("Test")) // commenting this out displays what key has been pressed.
{
if (e.alt)
{
if (e.type == EventType.KeyDown)
{
var k = e.keyCode;
Debug.Log("keyCode: " + k);
}
}
}
OnGUI gets called separately for each UI event type, possibly multiple times per frame.
If the player presses a key down, Unity will call OnGUI with Event.current.type == KeyDown, and Event.current.keyCode == keycode of the pressed key.
If the player clicks and releases on the button, Unity will call OnGUI with Event.current.type == MouseUp. During this invocation of OnGUI, Event.current.keyCode will not be valid because it’s only valid on invocations where Event.current.type is a key-related event.
OnGUI could be called many other times during the frame, too, such as when the player moves the mouse, or spins the scrollwheel, or when the GUI system wants to do a relayout or repaint.
Try this script:
using UnityEngine;
public class GUIButtonTest : MonoBehaviour
{
private bool isAlpha1Down = false;
private void OnGUI()
{
var e = Event.current;
// Check if the event type is KeyDown or KeyUp on Alpha1:
if (e.type == EventType.KeyDown && e.keyCode == KeyCode.Alpha1)
{
isAlpha1Down = true; // Remember that Alpha1 is down.
}
else if (e.type == EventType.KeyUp && e.keyCode == KeyCode.Alpha1)
{
isAlpha1Down = false; // Remember that Alpha1 is up.
}
// Always draw the button. It will only register a click if e.type is a mouse click.
if (GUILayout.Button("Test"))
{
Debug.Log("Button clicked. Is Alpha1 down? " + isAlpha1Down);
}
}
}