🏠 Home

Loops in Unity

Loops in Unity are a way to repeat actions in your code β€” for example, spawning enemies one by one, iterating through inventory items, or waiting until something happens. They let you avoid writing the same code over and over again by doing it automatically as many times as needed.

In C# and Unity, there are several types of loops: for, while, and foreach. Each works a bit differently, but the idea is the same: repeat as long as a condition is true.

πŸ” The for Loop

A for loop is a way to repeat the same block of code multiple times. You tell the computer: start from a certain value, check a condition, and update a counter each time. For example: "repeat 10 times" or "go through all elements from 0 to 5".

This type of loop is especially useful when you know in advance how many times something should happen β€” like creating 5 enemies, counting points, or drawing 10 platforms.

 
using UnityEngine;

public class CSharpScript : MonoBehaviour
{
  // Start is called once when the object starts
  void Start()
  {
    // Repeat 5 times
    for (int i = 0; i < 5; i++)
    {
      Debug.Log("Iteration #" + i);
    }
  }

  // Update is called once per frame
  void Update()
  {
    
  }
} 

In this example, we run a for loop that repeats 5 times. The variable i starts at 0 and increases by 1 each time. As long as i is less than 5, the loop continues, and we print the iteration number to the console.

This is how most simple repetitions work in Unity: you can iterate through levels, create objects, check arrays, and much more.

πŸ”„ The while Loop

A while loop runs as long as the condition remains true. It works like a check before every step: if the condition is true, we continue; if false, we exit the loop.

This type of loop is useful when you don’t know in advance how many times something should repeat β€” for example, waiting until the player reaches a target, or until an exit button is pressed.

 
using UnityEngine;

public class CSharpScript : MonoBehaviour
{
  int energy = 3;

  // Start is called once when the object starts
  void Start()
  {
    // Repeat while energy is greater than zero
    while (energy > 0)
    {
      Debug.Log("Energy left: " + energy);
      energy--;
    }
  }

  // Update is called once per frame
  void Update()
  {

  }
} 

In this example, the while loop runs as long as energy is greater than zero. On each step, we print the value to the console and decrease energy by one.

Once energy becomes zero, the condition is no longer true and the loop stops. This approach is common when the number of repetitions depends on some state β€” like remaining ammo or whether an enemy is still alive.

⚠️ Tip: Be careful with while loops in Unity!

If the condition never becomes false, the loop will be infinite and Unity may freeze or crash. This is especially dangerous if the loop runs inside Update().

Always make sure the variable in the condition is changing inside the loop. Or add a limit β€” like a maximum of 100 iterations β€” if you're not sure.

 
using UnityEngine;

public class CSharpScript : MonoBehaviour
{
  int energy = 10;

  // Start is called once when the object starts
  void Start()
  {
    while (true)
    {
      if (energy <= 0)
      {
        Debug.Log("Energy is depleted β€” exiting loop");
        break; // Exit the loop
      }

      Debug.Log("Energy left: " + energy);
      energy--;
    }
  }

  // Update is called once per frame
  void Update()
  {

  }
} 

Here the loop while (true) looks infinite, but there's a condition inside: if energy is less than or equal to zero, the break statement exits the loop.

This is useful when a loop should run "until something happens" β€” even if you don’t know exactly when. Just remember to include an exit condition!

πŸ”‚ The foreach Loop

A foreach loop lets you go through all elements in a collection β€” an array, list, or any other set. It automatically grabs each item in order, so you don’t need to count manually like in a for loop.

This is especially useful when you don’t care about the index and just want to go through everything β€” like all enemies, all buttons, or all items in an inventory.

 
using UnityEngine;

public class CSharpScript : MonoBehaviour
{
  string[] names = { "Anya", "Bob", "Sonya", "Mr. Hedgehog" };

  // Start is called once when the object starts
  void Start()
  {
    foreach (string name in names)
    {
      Debug.Log("Name: " + name);
    }
  }

  // Update is called once per frame
  void Update()
  {

  }
} 

In this example, we use foreach to loop through the names array. On each step, the name variable automatically receives the next value β€” first "Anya", then "Bob", then "Sonya", and of course, Mr. Hedgehog.

This approach is great when you just want to iterate over all elements without using counters. foreach makes it simple and readable.