[SOLVED] Is using a string name in place of a KeyCode acceptable as well?

At 5:30 in the video, you are instructed to make the input use the up arrow key.

On this page of the Unity docs, it lists two ways to tell the function what key you are using.

I used a string name (“up”), but he used a KeyCode (KeyCode.UpArrow).

Are both of these correct, or are the KeyCodes the only thing that should be used?

Hello @Michelle,

You can use either, but, there are some considerations.

When and where ever you use a string like this there is potential for mistake, if you have multiple locations in your code where ("up") was used for example. The compiler isn’t going to warn you about a type (uup) whilst you are coding. However, if you entered KeyCode.UupArrow you would be getting an error instantly.

The second paragraph on the page you linked to is very important also - at this stage on Number Wizard it doesn’t really matter too much, it is after all a gentle introduction, however, later on, should you want to allow a player to configure keys for a game, lets say for left / right / up / down movement, you can use the Input.GetAxis method instead, this will save you having to deal with checking strings or keycodes for all of the possibilities.

Ironically, these are still via “strings” so there is the potential for mistake, but a hugely reduced one.


See also;

1 Like

Thanks so much, @Rob! That’s exactly what I was looking for. :smiley:

1 Like

You are more than welcome :slight_smile: