Increment variable

How can i increment a variable? Let me explain:

bool key87;
bool key65;

i have these 2 variables, i want to access them by using “key” + the KeyCode pressed.
How can i do that?

What you want to do is called reflection, you can access any member of a class by it’s name and you can set the value for any field.

  1. Get a Type variable of the type of your script with GetType
  2. Make a string for the field (“key” + the key code)
  3. Get the field you want with the GetField(string) method of the Type variable
  4. Get the value of the field with GetValue and cast the value to bool

If you want to set the value there’s also a SetValue method on the field, you send the instance of the object you want to modify and the new value.

Anyway, this is not a good practice, reflection is slow, hard to code and maintain and you lose the advantages of using a typed language with scopes and visibility (you can even access private members with reflection). I’d check again your design, if you name a few variables “keyXX” just to hold the state of a key why not just check the state instead with Input.GetKey? If you need some other info then maybe an array of bool values would be better. Maybe you just need a few bools instead of 100, so the dictionary suggested in the comments would be better.