PREFABS & SPAWNING

Turn game objects into reusable templates and spawn them with code!

Course: Game On (9GAMZA) Lesson: T1 — L10 Time: ~75 min Outcomes: G5-1, G5-2, G5-4
TOTAL XP 0 / 50 XP
1
What Are Prefabs?
~10 min
+10 XP

Key Vocabulary

Prefab
A reusable template of a GameObject. Change the prefab = all copies update.
Instance
A copy of a prefab placed in the scene. Each instance can be tweaked individually.
Instantiate
The C# command to create a new copy (instance) of a prefab at runtime.
Spawning
Creating objects during gameplay (e.g. enemies appearing, bullets firing).
1.1
The Problem: Imagine you have 50 coins in your game. You want to change the coin sprite. Without prefabs, you'd edit ALL 50 coins one by one. That's terrible!
1.2
The Solution: Prefabs. A prefab is like a cookie cutter. You design the cookie cutter once, and every cookie comes out the same. Change the cutter = ALL cookies change.
Real-world analogy: A prefab is like a class in a school timetable — every student in the class gets the same schedule, but each student can still have their own lunch preference.
1.3
Create your first prefab:
  • Open your Unity project from last lesson
  • Create a new sprite: Right-click in Hierarchy → 2D Object → Sprites → Circle
  • Rename it "Coin" in the Inspector
  • Change its colour to yellow (Sprite Renderer → Color)
  • Scale it to (0.5, 0.5, 1) in Transform
1.4
Turn it into a Prefab: Drag your "Coin" from the Hierarchy into the Project window (Assets folder). The name in the Hierarchy turns blue — that means it's now a prefab instance!
What happened? Unity created a .prefab file in your Assets. The object in the scene is now an instance of that prefab.
1.5
Test the power of prefabs:
  • Drag the Coin prefab from Project into the Scene 3 more times — you now have 4 coins
  • Position them at different spots in your level
  • Now double-click the prefab in the Project window to open Prefab Edit Mode
  • Change the colour to orange
  • Click the back arrow at the top of the Hierarchy to exit Prefab Mode
  • All 4 coins should now be orange! That's the power of prefabs.
Checkpoint: I have a Coin prefab in my Project, and 4 instances in my scene that all match.
2
Prefab Overrides & Components
~10 min
+10 XP
2.1
Override an instance: Select ONE coin in the scene. Change its colour to red. Notice: only THAT coin changes, not the prefab. This is called an override.
Override = a change that ONLY applies to one instance. The prefab stays the same. You'll see a blue bar next to overridden properties in the Inspector.
2.2
Apply or Revert: With the overridden coin selected, click Overrides → Apply All (at the top of Inspector) to push changes TO the prefab. Or click Revert All to undo your changes and match the prefab again.
Apply = make ALL instances look like this one. Revert = make this instance look like the prefab again.
2.3
Add a Collider to the Prefab: This is key — we need coins to be collectible later!
  • Double-click the Coin prefab to open Prefab Edit Mode
  • Click Add Component → Physics 2D → Circle Collider 2D
  • Tick Is Trigger (we want to detect overlap, not block movement)
  • Exit Prefab Mode — ALL coins now have a trigger collider!
2.4
Tag the Prefab:
  • In Prefab Edit Mode, go to the top of Inspector → Tag → Add Tag
  • Click +, type "Coin", click Save
  • Go back to the prefab, set its Tag to "Coin"
  • Exit Prefab Mode — all instances are now tagged!
💡 Pro Tip: Always add components/tags to the PREFAB (via Prefab Edit Mode), not to individual instances. This keeps everything consistent.
Checkpoint: My Coin prefab has a Circle Collider 2D (Is Trigger), and is tagged "Coin".
3
Collecting Coins with Code
~15 min
+10 XP
3.1
Open your PlayerController script. We'll add coin collection to the player, not the coin. Why? Because the player is the one moving — they trigger the collision.
3.2
Add a score variable at the top of your class (with your other variables):
public int score = 0;
3.3
Add the OnTriggerEnter2D method below your Update method:
void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Coin")) { score++; Debug.Log("Coins: " + score); Destroy(other.gameObject); } }
Line by line:
OnTriggerEnter2D — called when something with Is Trigger enters our collider
CompareTag("Coin") — only react to objects tagged "Coin"
score++ — add 1 to our score (same as score = score + 1)
Debug.Log — print score to Console (we'll add UI later)
Destroy(other.gameObject) — remove the coin from the scene
3.4
Save and Test!
  • Save your script (Ctrl+S)
  • Go back to Unity, press Play
  • Move your player into the coins
  • Check the Console window — you should see "Coins: 1", "Coins: 2", etc.
  • The coins should disappear when touched!
Coins don't disappear? Check: (1) Coin has Circle Collider 2D with Is Trigger ON. (2) Coin is tagged "Coin" (case sensitive!). (3) Player has a Collider2D AND a Rigidbody2D. All three are needed for triggers to work!
Checkpoint: When my player touches a coin, the coin disappears and the score increases in the Console.
4
Spawning Objects with Code
~25 min
+10 XP

Key Vocabulary

Instantiate()
Creates a new instance of a prefab at a specific position and rotation.
Spawner
A script that creates objects at intervals or on events.
InvokeRepeating
Calls a method repeatedly at a set time interval.
Random.Range
Generates a random number between two values.
4.1
Create a new empty GameObject: Right-click in Hierarchy → Create Empty. Name it "CoinSpawner". Position it above the screen (e.g. Y = 6).
4.2
Create a new script: With CoinSpawner selected, click Add Component → New Script. Name it "Spawner". Double-click to open it.
4.3
Delete the default code and type this complete Spawner script:
using UnityEngine; public class Spawner : MonoBehaviour { public GameObject prefabToSpawn; public float spawnInterval = 2f; public float spawnRangeX = 5f; void Start() { InvokeRepeating("SpawnObject", 1f, spawnInterval); } void SpawnObject() { float randomX = Random.Range(-spawnRangeX, spawnRangeX); Vector3 spawnPos = new Vector3(randomX, transform.position.y, 0); Instantiate(prefabToSpawn, spawnPos, Quaternion.identity); } }
Line by line:
prefabToSpawn — drag ANY prefab here in the Inspector
spawnInterval — seconds between each spawn (tune in Inspector!)
spawnRangeX — how far left/right objects can spawn
InvokeRepeating("SpawnObject", 1f, spawnInterval) — start after 1 second, then repeat every spawnInterval seconds
Random.Range(-spawnRangeX, spawnRangeX) — random X position
Instantiate(prefab, position, rotation) — create the object!
Quaternion.identity — no rotation (default orientation)
4.4
Connect the Prefab:
  • Save the script, go back to Unity
  • Select the CoinSpawner in the Hierarchy
  • In the Inspector, you'll see Prefab To Spawn — it says "None"
  • Drag your Coin prefab from the Project window into that slot
  • Set Spawn Interval to 2 and Spawn Range X to 7
4.5
Press Play! Coins should rain from the top! Move your player to collect them. Check the Console for your score.
Problem: The coins pile up forever! We'll fix this by adding a destroy timer. See step 4.6.
4.6
Auto-destroy spawned objects: Open your Spawner script and change the Instantiate line:
void SpawnObject() { float randomX = Random.Range(-spawnRangeX, spawnRangeX); Vector3 spawnPos = new Vector3(randomX, transform.position.y, 0); GameObject spawned = Instantiate(prefabToSpawn, spawnPos, Quaternion.identity); Destroy(spawned, 5f); // Destroy after 5 seconds if not collected }
Destroy(object, delay) — the second parameter is the delay in seconds. After 5 seconds, uncollected coins vanish automatically. This prevents memory issues!
4.7
Create an Enemy Prefab: Now make a second prefab!
  • Create a new sprite: 2D Object → Sprites → Square
  • Name it "Enemy", colour it red
  • Add Box Collider 2D (Is Trigger ON)
  • Add Tag: "Enemy"
  • Drag to Project to make it a prefab
  • Delete the scene instance (we'll spawn it instead)
4.8
Create a second Spawner:
  • Right-click in Hierarchy → Create Empty → name "EnemySpawner"
  • Add the Spawner script (same script, reused!)
  • Drag the Enemy prefab into Prefab To Spawn
  • Set interval to 3 (slower than coins)
4.9
Handle enemy collision: In your PlayerController, add inside OnTriggerEnter2D:
void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Coin")) { score++; Debug.Log("Coins: " + score); Destroy(other.gameObject); } if (other.gameObject.CompareTag("Enemy")) { lives--; Debug.Log("Lives: " + lives); Destroy(other.gameObject); if (lives <= 0) { Debug.Log("GAME OVER!"); } } }
Make sure you have public int lives = 3; declared at the top with your other variables!
Checkpoint: Coins spawn and can be collected. Enemies spawn and damage the player. Score and lives show in Console.
5
Extension Challenges
~15 min
+10 XP
🏆 Challenge 1: Moving Enemies — Create a new script called "MoveDown". In Update, add: transform.Translate(Vector3.down * speed * Time.deltaTime); with a public float speed = 3f. Attach it to your Enemy prefab. Now enemies fall toward the player!
🏆 Challenge 2: Power-Up Prefab — Create a green circle prefab tagged "PowerUp". When collected, set a bool isShielded = true and ignore enemy damage for 5 seconds. Use Invoke("RemoveShield", 5f) to turn it off.
🏆 Challenge 3: Difficulty Scaling — Add a variable public float difficultyMultiplier = 0.95f; to the Spawner. After each spawn, multiply spawnInterval by difficultyMultiplier. The game gets faster over time! Use CancelInvoke(); InvokeRepeating(...); to restart with new interval.
🏆 Challenge 4: Object Pooling — Research "Object Pooling" in Unity. Instead of Instantiate/Destroy (which is slow), pre-create objects and reuse them. This is how real games handle hundreds of bullets!
🚀 Boss Challenge: Create a spawner that spawns a MIX of coins, enemies, and power-ups at random. Coins = +1 score, Enemies = -1 life, Power-ups = +1 life. Make a complete mini-game!