Hi all, the for loop has me lost, and in particular I don’t understand this section of code:
for(int index = 0; index < nextStates.Length; index++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + index))
{
state = nextStates[index];
}
I am particularly confused about: if (Input.GetKeyDown(KeyCode.Alpha1 + index))
I don’t understand how this code still lets Alpha2 and Alpha3 work - somehow the program still works when you hit Alpha2 or Alpha3, but how can they work when they aren’t even mentioned?
Sorry - this isn’t explained perfectly, but I’m totally lost.
I came up with this other secondary solution which is more understandable for me, but I’m guessing the solution with for loop is more used as there is less code and because of that seems more efficient.
if (Input.GetKeyDown(KeyCode.Alpha1) && nextStates.Length >= 1)
{
state = nextStates[0];
}
else if (Input.GetKeyDown(KeyCode.Alpha2) && nextStates.Length >= 2)
{
state = nextStates[1];
}
else if (Input.GetKeyDown(KeyCode.Alpha3) && nextStates.Length >= 3)
{
state = nextStates[2];
}
Basically the same as for loop, not letting the access to indexes which do not exist.
Regards.
It’s a little confusing and took me a while to figure out, but what KeyCode.Alpha1 returns is actually a number, in this case 49, KeyCode.Alpha2 = 50 and so on.
So what the for-loop does is check if the value pressed is 49+i, where:
When nextStates.length = 1, the code just checks for KeyCode.Alpha1 + 0
When .length = 2 the code checks for KeyCode.Alpha1 + 0 and KeyCode.Alpha1 + 1
When .length=3 it checks for KeyCode.Alpha1 + 0,1 and 2.
It’s a little more complex than this since KeyCode is what’s called an enum, which is sort of a group or a list of values, but that’s the easy way of thinking about it.
When I read what I’ve written here, it looks a little confusing, but I hope it makes some sense.
This is a fairly old trick and is often used even outside of languages that have Enum support.
It was often used for reading characters as typed input (rather than the keycode which is more related to the keyboard presses regardless of whether they produce a character or not).
A lot of time this meant referencing the ASCII table, and if you look up the "dec"imal column and locate row number 49 - guess what it points to? Number 1:
Then you’ll notice the rest of the numbers (with 0 at position/row 48) follow it.
It’s quicker and there are more efficiencies available to work with a known range of values that map to the inputs you want to check, than it is to write out a long list of if() statements to cater for each one.