, ,

I’ve heard some developers complain that Unity only updates input once per frame, and that they find themselves in some circumstance where they need more accurate information about when exactly a key was pressed.

As it turns out, there is a hidden way to get at this information: Unity’s Event class.

From the scripting reference:

Events correspond to user input (key presses, mouse actions), or are UnityGUI layout or rendering events.

For each event OnGUI is called in the scripts; so OnGUI is potentially called multiple times per frame. Event.current corresponds to “current” event inside OnGUI call.

If you’re the sort of person who avoids OnGUI whenever possible, you probably never knew about this feature!

This gets us a function call for each key press (and release), among other things. Now, we just need timing information. Lucky for us, Time.realtimeSinceStartup still returns useful data between frames.

You now know which key was pressed and exactly when it was pressed. It’s easy enough to pass that data along to other parts of your game; what you do with it after that is up to you.

Here’s a quick-and-dirty proof of concept: HighFreqInput.cs.