Menu
CoddyTech

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 icon

Challenge

Medium

Lay a floor of 12 tiles: 4 columns, 3 rows.

  1. In Start(), replace PlaceTile(0, 0); with for (int column = 0; column < 4; column++).
  2. Inside its braces, write for (int row = 0; row < 3; row++), and call PlaceTile(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

Practice on your own: Unity playground