input – How can I get what key was pressed in Unity?


I’m working on a chat that will immediately record input when any (compatible) key is pressed, so I need to record the keys pressed and turn them into a string.

1) Listen to every key-press with a script and push it inside a Text component

I like this one most, because the chat is simple enough that I’m better off with a custom Input Field component, and I get all the control I need.

However, I don’t know how to get what key was pressed in a frame, short of checking for every single one (and the shift modifier, too). This is inefficient both for me, the developer, and the computer.

2) Automatically focus an Input Field when any key is pressed

Unity has a handy Input.anyKey boolean field that’s true whenever any key is pressed, but I need to save that first key press and insert it manually into the Input Field or else it will be lost, as the Input Field only listens for key-presses once it’s in focus.

That means I need a way to record key presses, and then we’re back to solution #1.