Mestik 78
Mestik 78

Reputation: 301

How do I detect if the key of a variable is pressed?

I´m making a game that creates a random key that you have to press. I have an array with the letters from where it takes one randomly. I want to detect if the key is pressed so I did this:

if (Input.GetKey(KeyCode.lettre))

but with letter = "A" for example, it will do this:

if (Input.GetKey(KeyCode."A"))

How do I get this?

if (Input.GetKey(KeyCode.A))

Upvotes: 1

Views: 112

Answers (1)

Sweeper
Sweeper

Reputation: 273380

GetKey can be called with a string, so you could just do:

if (Input.GetKey(letter)) // assuming letter is a string

You might need letter to be lowercase for this to work. See the list of key names here.


Alternatively, you could use Enum.Parse to convert your string to an enum value:

if (Input.GetKey((KeyCode)Enum.Parse(typeof(KeyCode), letter)))

Upvotes: 1

Related Questions