Learn Unity and C# by Making Games / C# Fundamentals
Repeat actions safely with for and while loops.
for loops and while loops.A loop lets you repeat a block of code multiple times.
1for (int i = 0; iint i = 0 → Start at 0i → Keep going as long as i is less than 5i++ → Add 1 each timeThis prints 5 messages - once per enemy. Great for counted repetition.
1int lives = 3;2 3while (lives > 0)4{5 Debug.Log("Still alive!");6 lives--;7}lives is more than 0.lives.Be careful! A while loop won’t stop unless the condition eventually becomes false. That’s how infinite loops happen 🌀
Here’s a simple for loop in Unity that spawns 5 cubes in a row:
1using UnityEngine;2 3public class Spawner : MonoBehaviour4{5 public GameObject cubePrefab;6 7 void Start()8 {9 for (int i = 0; iUse 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 |
1while (true)2{3 Debug.Log("Wheeeeee!");4}for loops = best for doing things a set number of timeswhile loops = best for doing something until a condition changesStarSpawner.csStart(), use a for loop to spawn 10 stars in a linei * 1.5f)Bonus: Add a public int starCount to control how many are spawned.
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.
Keep it small enough to finish in five minutes, then write down what changed and what Unity showed you.
What is the best next step after reading a lesson section?
download
Use this before starting a new Unity prototype.
reference
Official reference for Unity editor concepts, components, and workflows.
reference
The fastest way to verify classes, methods, and Unity-specific behavior.
download
Checklists and creator resources for keeping projects moving.