- Home /
For loop in "Writing the Board Manager" 2d Roguelike confusion
There is a line I have been trying to figure out but just can't in the 2d roguelike tutorial writing the board manager:
for(int x = 1; x < columns-1; x++)
{
//Within each column, loop through y axis (rows).
for(int y = 1; y < rows-1; y++)
{
//At each index add a new Vector3 to our list with the x and y coordinates of that position.
gridPositions.Add (new Vector3(x, y, 0f));
}
}
I don't get it because if each time it goes through x and y are added by 1, how can it list every coordinate like (1,2), (1,3) etc if it adds one to x and y at the same time? Wouldn't it be just (1,1), (2,2), (3,3) etc.?
Answer by HarshadK · Aug 03, 2017 at 04:58 AM
The program first enters outer loop (int x...), gets the value of x for first iteration i.e. x will be 1 in this case then it enters inner loop (int y...). Then the inner y loop finishes all its iteration for value of y. Then again the control is passed to outer loop which goes to next iteration value i.e. x will be 2 and it again enters the inner loop and finishes the inner loop and then control goes back to inner loop and this process is repeated on and on till the end condition is reached.
For example, when the loops start, Enter outer loop => x = 1, instantly enter inner loop => y = 1 This would give us (1, 1) Now inner loop continues while value of x remaining the same i.e. 1. So x = 1 & y = 2 => (1, 2). This will continue till all y values are satisfied. Then x will be incremented => x = 2. And inner loop now starts again from it initial value i.e. y = 1, which now gives (2, 1). Now inside inner loop itself y = 2, which gives (2, 2).
This will get repeated till x reaches its target value. Hope you understand the point.
Your answer

Follow this Question
Related Questions
How does Unity figure out generic component type as Wall in Project: 2D Roguelike tutorial? 0 Answers
In the tutorial of the 2D Roguelike game, where is the player gameobject instantiated in the code? 2 Answers
2D Roguelike - moving onto enemies 3 Answers
Why is the boundary not working? 1 Answer
How to make a slider menu 1 Answer