Loops Inside Loops
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 38 of 85.
A row needs one loop. A whole floor, rows and columns, needs a loop inside a loop:
for (int column = 0; column < 3; column++)
{
for (int row = 0; row < 2; row++)
{
Debug.Log(column + ", " + row);
}
}For every round of the outer loop, the inner loop runs all the way through. So this writes 0, 0 and 0, 1, then 1, 0 and 1, 1, then 2, 0 and 2, 1: 3 columns times 2 rows, 6 lines in all.
The two loops need counters with different names. Here they are named for what they count, column and row, which makes the code easier to read than i and j.
Challenge
MediumLay a floor of 12 tiles: 4 columns, 3 rows.
- In
Start(), replacePlaceTile(0, 0);withfor (int column = 0; column < 4; column++). - Inside its braces, write
for (int row = 0; row < 3; row++), and callPlaceTile(column, row);inside that inner loop.
Press Play: a floor of 4 by 3 tiles appears. Then Check.
Try it yourself
using UnityEngine;
public class TileFloor : MonoBehaviour
{
void Start()
{
// Lay 4 columns and 3 rows of tiles.
PlaceTile(0, 0);
}
void PlaceTile(int column, int row)
{
GameObject tile = GameObject.CreatePrimitive(PrimitiveType.Cube);
tile.name = "Tile";
tile.transform.position = new Vector3(column * 1.1f - 1.65f, 0.1f, row * 1.1f);
tile.transform.localScale = new Vector3(1, 0.2f, 1);
tile.GetComponent<Renderer>().material.color = new Color(0.85f, 0.85f, 0.9f);
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector7Loops and Methods
Repeat with forLoops Inside LoopsWrite a MethodMethods That AnswerArraysRecap: Staircase2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground