Iterating through a custom keycode enum for input detection
I am trying to read in key inputs from the player and store them. I had a working method of doing this, but every key press it needs to loop through every single keycode until the keycode that is pressed is detected. There are 300+ keycodes, meaning this slows down this loop quite a bit. I would like to use a custom enum that stores the relevant keycodes I am using and to loop through these keys in the same way I am doing now.
Here is my enum
enum theKeys
{
W = 0,
A,
S,
D,
Space
}
Here is my check for input along with the foreach loop through the enum
if (Input.anyKeyDown || Input.anyKey)
{
foreach(KeyCode code in theKeys.GetValues(typeof( KeyCode )) )
{
...
}
}
When I loop through this custom enum it still loops through all 326 keycodes. If I interpret an enum as holding keycodes does it default to using the system.enum? Should I store the ascii values or the string literal of the keys then convert them after the foreach to a keycode? Thanks!
Answer by Hellium · Dec 17, 2018 at 05:52 PM
Why do you need to use an enum? I suggest you to use a simple array instead:
public KeyCode[] KeyCodes;
// ...
for( int index = 0 ; index < KeyCodes.Length ; ++index )
{
if( Input.GetKey( KeyCodes[index] ) || Input.GetKeyDown( KeyCodes[index] ) )
{
Debug.Log( KeyCodes[index] + " has been pressed" ) ;
}
}
Your answer
Follow this Question
Related Questions
How to make custom input key presses 0 Answers
How to change Button input to Keyboard input? 1 Answer
if (input.Getkey(Keycode) returns true forever after pressing the key once? 1 Answer
How do I save separate keycodes presses at same time and store for use later in update? 0 Answers
How to detect Keycode.Return using an Android bluetooth keyboard? 2 Answers