I was setting up a double-tap(-hold) mechanism for my keyboard keys. Decided I’d use the Events in OnGUI for capturing my KeyDowns, rather than using Input, since this way I could fetch which button was pressed.
So I went about this like so
if (currentEvent.type == EventType.KeyDown) {
float currentTime = Time.time;
KeyCode currentKey = currentEvent.keyCode;
if (!doubleTapped currentKey == lastKeyPressed currentTime <= (timeOfLastKeyPress + doubleTapTimeThreshold)) {
doubleTapped = true;
}
timeOfLastKeyPress = currentTime;
lastKeyPressed = currentKey;
}
else if (currentEvent.type == EventType.KeyUp) {
doubleTapped = false;
}
Worked pretty alright, for the arrow keys atleast. But when testing other keys, I found some strange behaviour.
Alphabet keys for instance, wouldn’t doubletap this way.
So I set up this simple test
void OnGUI()
{
Event currentEvent = Event.current;
if (currentEvent.isKey currentEvent.type == EventType.KeyDown) {
Debug.Log(currentEvent.keyCode);
}
}
Throw it on an empty object and try it out.
Arrow keys, pagedown, and some others work as expected. But Space, Enter, and alphabet keys result in 2 debug lines. The first is the correct KeyCode enum, and the second holds ‘None’. So that’s a second event somehow, and a faulty KeyCode to boot.
This can’t be desired behaviour…
And on a side note: Since this does not seem to be working, how would I go about ‘enabling’ double tapping for n-number of keys?
Say ‘DidIRegisterADoubleTap(KeyCode pressedKey) { /magic?/ }’ ?
edit: Also it is important to note that while Input.GetKeyDown(keyCode) only returns true once; the first frame in which the key was pressed. Where EventType.KeyDown gets triggered once upon first pressing the key, and then repeatedly triggers when holding (same default windows behaviour when press/holding a key).
In fact the behaviour from the Input variant would be desired over the other…