Menu
CoddyTech

Repeat with for

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 37 of 85.

A for loop runs its lines again and again, counting as it goes:

for (int i = 0; i < 5; i++)
{
    Debug.Log("Round " + i);
}

The parentheses hold three parts: where the counter starts (int i = 0), the condition to keep going (i < 5) and what happens after each round (i++). This loop runs 5 times, with i at 0, 1, 2, 3 and 4.

You can do math with the counter: i * 2 gives 0, 2, 4, 6 and 8.

PlaceCrate is a method written for you: a named group of lines. PlaceCrate(3); runs them and puts a crate at x = 3. You will write your own methods later in this chapter.

challenge icon

Challenge

Medium

Place 5 crates in a row with a for loop.

  1. In Start(), replace PlaceCrate(0); with for (int i = 0; i < 5; i++) and its braces.
  2. Inside the loop, call PlaceCrate(i * 2 - 4);, which gives x = -4, -2, 0, 2 and 4.

Press Play: five crates stand in a row, 2 apart. Then Check.

Try it yourself

using UnityEngine;

public class CrateRow : MonoBehaviour
{
    void Start()
    {
        // Place 5 crates: at x = -4, -2, 0, 2 and 4.
        PlaceCrate(0);
    }

    void PlaceCrate(float x)
    {
        GameObject crate = GameObject.CreatePrimitive(PrimitiveType.Cube);
        crate.name = "Crate";
        crate.transform.position = new Vector3(x, 0.5f, 0);
        crate.GetComponent<Renderer>().material.color = new Color(0.8f, 0.55f, 0.3f);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground