1
\$\begingroup\$

Is there a way to get the time of an input event (a key or button press) to a higher degree of accuracy than the Update call, maybe by subscribing to input events and handling them immediately?

\$\endgroup\$
  • 1
    \$\begingroup\$ Out of interest, why do you need such highly accurate input? Your purpose will tell us how accurate exactly the input needs to be. \$\endgroup\$ – Alex F Jun 19 '19 at 5:32
1
\$\begingroup\$

Using OnGUI() and Event.current you can get the exact moment that a key is pressed. OnGUI() is one of the few things that is not tied to framerate like the update function is. This is why using OnGUI() will give you a much more accurate time than the update function.

You can then do something like this:

void OnGUI()
{
    if (Event.current.isKey)
    {
        Debug.Log("Key pressed at time " + Time.realtimeSinceStartup);
    }
}

which will put the time a key was pressed, released, and typed in console.

I'm using Time.realtimeSinceStartup here because this reports time based on the system timer unlike Time.time does.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Does this require a workaround to make sure some GUI always has focus, so these events can be used outside of the context of GUI? \$\endgroup\$ – Tom Quinn Jun 19 '19 at 6:05
  • 1
    \$\begingroup\$ All this requires is that the game has focus. There is no need for any UI elements, canvases, or event systems. \$\endgroup\$ – DragonHeart000 Jun 19 '19 at 6:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.