Hi, I’m kind of getting perplexed about writing an “if statements” inside a “for loop”. here is the code that I don’t understand.
" for (int i = 0; i < 10; i++) {
if (Input.GetKeyDown(KeyCode.A)) {
print(i);
}
}"
So what is puzzling about this is that i (which is the variable in the for loop) can be any number under 10 depending on which iteration we are on for example if we are on the 9 iteration i (which is the variable in the for loop) would be 8 right or let’s say we are on the 5 iteration i would be 4 but when we are saying that if we click “A” on the keybord it only prints “0 1 2 3 4 5 6 7 8 9” but what I expected it to print was that it will print out i(which is the variable in the for loop) in that specific iteration for example lets say i (which is the variable in the for loop) is currently in the 6th iteration which means its 5 and we click “A” on the keybord it doesn’t print out 5 it prints out "0 1 2 3 4 5 6 7 8 9 " do you know why this is happening? and the second thing that I’m getting confused about is lets say in each iteration in the for loop we never clicked “A” on the keybord and then the loop ends and then when I click “A” on the keybord it still prints out "0 1 2 3 4 5 6 7 8 9 " which is not what I expected because I expected it to not print out nothing because the loop has ended which means that the if statement will not work and it will not execute because the loop has ended do you have an explenation for this thank you.
This is not directly connected but it is made by breakage so it will help you here is the link
Url:How to Program in C# - Loops (E04) - YouTube
It may help you understand loops much better.
GetKeyDown() is true in the frame in which it’s pressed.
So in the frame that it triggers the keypress it also processes the entire loop, making every iteration of the loop share the same keypress of that 1 frame which causes it to print each iteration, because until the next frame, GetKeyDown() is true.
What I do find odd is that it always gets the key before any iterations of the loop, as opposed to printing say (5,6,7,8,9) if you happen to hit the key in the middle of it’s iterations.
Basically you don’t want to get key inputs during a for loop.
What is it you are trying to accomplish BTW?
A second question would be where are you running the loop? Update()? If so that is the reason you see it print, since Update() is a loop itself and means that every frame a new for loop begins to process.