🔁 Loops – When You Want Something to Happen Again… and Again

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

What’s happening here?

  • int i = 0 → Start at 0
  • i < 5 → Keep going as long as i is less than 5
  • i++ → Add 1 each time

This prints 5 messages — once per enemy. Great for counted repetition.


🔁 while Loop – Repeat Until a Condition Changes

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:

  • 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 repeatYou don’t know how long it’ll last
You’re counting somethingYou’re waiting for a condition
Performance loopsWait timers, player input

💥 Common Mistake: Infinite Loops

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 times
  • while 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

  1. Create a prefab (e.g. a star sprite)
  2. Create a script StarSpawner.cs
  3. In Start(), use a for loop to spawn 10 stars in a line
  4. 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#