Imagine spawning 5 enemies, checking every platform for coins, or counting down a timer.
Typing the same code 10 times? Nah.
That’s what loops are for.
In this lesson, we’ll cover the two most common types of loops in C#:for
loops and while
loops.
🔄 What is a Loop?
A loop lets you repeat a block of code multiple times.
It’s like telling Unity: “Hey, do this thing again — but only until I say stop.”
🎯 for
Loop – Counted Repetition
for (int i = 0; i < 5; i++)
{
Debug.Log("Spawning enemy #" + i);
}
What’s happening here?
int i = 0
→ Start at 0i < 5
→ Keep going as long asi
is less than 5i++
→ Add 1 each time
This prints 5 messages — once per enemy. Great for counted repetition.
🔁 while
Loop – Repeat Until a Condition Changes
int lives = 3;
while (lives > 0)
{
Debug.Log("Still alive!");
lives--;
}
This runs as long as lives
is more than 0.
Each time through, it prints the message and decreases lives
.
Be careful! A while
loop won’t stop unless the condition eventually becomes false. That’s how infinite loops happen 🌀
🧪 Unity Example – Spawning Objects with a Loop
Here’s a simple for
loop in Unity that spawns 5 cubes in a row:
using UnityEngine;
public class Spawner : MonoBehaviour
{
public GameObject cubePrefab;
void Start()
{
for (int i = 0; i < 5; i++)
{
Vector3 spawnPosition = new Vector3(i * 2, 0, 0);
Instantiate(cubePrefab, spawnPosition, Quaternion.identity);
}
}
}
- Attach this script to an empty GameObject
- Assign a prefab in the Inspector
- Hit play and voilà – five glorious cubes
🧠 When to Use What?
Use for when… | Use while when… |
---|---|
You know how many times to repeat | You don’t know how long it’ll last |
You’re counting something | You’re waiting for a condition |
Performance loops | Wait timers, player input |
💥 Common Mistake: Infinite Loops
while (true)
{
Debug.Log("Wheeeeee!");
}
Unless you’re a fan of frozen editors, don’t do this without a break condition!
Unity will get stuck, and you’ll become best friends with the Task Manager.
🧠 Recap
for
loops = best for doing things a set number of timeswhile
loops = best for doing something until a condition changes- Combine loops with other logic for powerful effects
- Loops are perfect for spawning, timers, and repeating animations
🧪 Mini Challenge: Make a Star Row
- Create a prefab (e.g. a star sprite)
- Create a script
StarSpawner.cs
- In
Start()
, use afor
loop to spawn 10 stars in a line - Use the loop variable to space them evenly (like
i * 1.5f
)
Bonus: Add a public int starCount
to control how many are spawned.
🚀 What’s Next?
You’ve now got variables, methods, logic, and loops! It’s time to combine everything into a simple class to represent real objects in your game.
👤 Go to Lesson 11 → Classes and Objects in Unity C#