Lesson Overview
In this lesson, students create a simple 2D game named Collect the Coins. The player moves with WASD or arrow keys, picks up coins by touching them, and earns one point for each coin collected.
Key concepts: Triggers, collectible objects, OnTriggerEnter2D(), CompareTag(), Destroy(), and basic score tracking.
Learning Objectives
- Create collectible objects from 2D sprites.
- Add and configure Collider2D components.
- Use OnTriggerEnter2D() to detect overlapping objects.
- Identify the Player using tags.
- Remove collectibles using Destroy().
- Track collected coins with a score manager.
- Test and debug a working game.
Part 1 — Create the Unity Project
Step 1: Create a New Project
- Launch Unity Hub and click New Project.
- Select a 2D template, such as 2D Core or Universal 2D.
- Name the project
PX_CollectCoins_L11_lastname. - Select
C:\UnityProjectsas the project location. - Click Create Project.
Step 2: Save the Scene
- Choose File → Save As or Save Scene As.
- Save the scene as
CoinCollectorSceneinAssets/Scenes.
Part 2 — Create the Player
Step 3: Add a Player Sprite
- Right-click in the Hierarchy and choose 2D Object → Sprites → Square.
- Rename the object
Player. - Set Position to
(0, 0, 0)and Scale to(0.8, 0.8, 1). - In Sprite Renderer, set its color to blue.
Step 4: Configure Physics
- Select
Playerand click Add Component. - Add a Box Collider 2D.
- Add a Rigidbody 2D.
- Use the following settings:
| Property | Value |
|---|---|
| Body Type | Kinematic |
| Gravity Scale | 0 |
| Simulated | Enabled |
Step 5: Assign the Player Tag
- Select
Player. - In the Inspector, open the Tag drop-down.
- Choose the built-in Player tag.
Part 3 — Program Player Movement
Step 6: Create the Script
- Create an
Assets/Scriptsfolder. - Inside it, create a MonoBehaviour C# script called
PlayerMovement. - Open the script and replace its contents with the code below.
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
void Update()
{
if (Keyboard.current == null)
{
return;
}
float moveX = 0f;
float moveY = 0f;
if (Keyboard.current.aKey.isPressed ||
Keyboard.current.leftArrowKey.isPressed)
{
moveX = -1f;
}
if (Keyboard.current.dKey.isPressed ||
Keyboard.current.rightArrowKey.isPressed)
{
moveX = 1f;
}
if (Keyboard.current.wKey.isPressed ||
Keyboard.current.upArrowKey.isPressed)
{
moveY = 1f;
}
if (Keyboard.current.sKey.isPressed ||
Keyboard.current.downArrowKey.isPressed)
{
moveY = -1f;
}
Vector2 direction = new Vector2(moveX, moveY);
direction = direction.normalized;
transform.position +=
(Vector3)(direction * moveSpeed * Time.deltaTime);
}
}
Step 7: Attach and Test Movement
- Save the script and return to Unity.
- Drag
PlayerMovement.csonto the Player in the Inspector. - Set Move Speed to
5. - Press Play and test using WASD and arrow keys.
Part 4 — Create the Coins
Step 8: Create the First Coin
- Right-click in the Hierarchy and choose 2D Object → Sprites → Circle.
- Rename it
Coin. - Change Sprite Renderer color to yellow or gold.
- Set Scale to
(0.5, 0.5, 1). - Set Position to
(2, 1, 0).
Step 9: Add a Trigger Collider
- Select
Coin. - Add a Circle Collider 2D component.
- Enable its Is Trigger checkbox.
The coin can now detect the player's overlap without physically blocking movement. The player's Rigidbody2D makes trigger events possible.
Step 10: Duplicate the Coins
- Select the Coin and press Ctrl + D to duplicate it.
- Move each duplicate to a different location.
- Use the following suggested coordinates:
| Coin | X | Y |
|---|---|---|
| Coin 1 | 2 | 1 |
| Coin 2 | -2 | 2 |
| Coin 3 | 3 | -2 |
| Coin 4 | -3 | -1 |
| Coin 5 | 0 | 3 |
Part 5 — Program Coin Collection
Step 11: Create CoinCollect.cs
Create a new C# script in Assets/Scripts called CoinCollect. Enter this code:
using UnityEngine;
public class CoinCollect : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Coin Collected!");
Destroy(gameObject);
}
}
}
Step 12: Attach the Script and Test
- Attach
CoinCollect.csto every coin. - Press Play and move the Player toward a coin.
- Confirm that the coin disappears and the Console displays
Coin Collected!. - Collect the remaining coins.
Part 6 — Understand the Code
| Code | What It Does |
|---|---|
OnTriggerEnter2D() |
Runs when an eligible 2D collider enters this object's trigger. |
Collider2D other |
Identifies the other collider entering the trigger. |
CompareTag("Player") |
Checks whether that object has the Player tag. |
Debug.Log() |
Displays information in the Unity Console. |
Destroy(gameObject) |
Removes the coin GameObject that owns the script. |
Programming concept: if (other.CompareTag("Player")) checks a condition. When the condition is true, the code inside the braces executes and destroys the coin.
Part 7 — Add a Coin Counter
Step 13: Create ScoreManager.cs
Create the script below in Assets/Scripts.
using UnityEngine;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager instance;
public int score = 0;
void Awake()
{
instance = this;
}
public void AddCoin()
{
score++;
Debug.Log("Coins Collected: " + score);
}
}
Step 14: Add the ScoreManager to the Scene
- Right-click in the Hierarchy and select Create Empty.
- Rename the new object
ScoreManager. - Attach
ScoreManager.csto it.
Step 15: Update CoinCollect.cs
Replace the earlier code with this version:
using UnityEngine;
public class CoinCollect : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
ScoreManager.instance.AddCoin();
Destroy(gameObject);
}
}
}
Step 16: Test the Score
- Press Play.
- Collect all five coins.
- Verify that the Console counts upward from 1 to 5.
Coins Collected: 1
Coins Collected: 2
Coins Collected: 3
Coins Collected: 4
Coins Collected: 5
Part 8 — Optional Challenge: Display the Score on Screen
- Choose UI → Text - TextMeshPro in the Hierarchy.
- Import TMP Essentials if prompted.
- Rename the text object
ScoreTextand position it in the top-left corner of the Canvas. - Set its initial text to
Coins: 0. - Replace
ScoreManager.cswith the script below:
using UnityEngine;
using TMPro;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager instance;
public int score = 0;
public TMP_Text scoreText;
void Awake()
{
instance = this;
UpdateScoreText();
}
public void AddCoin()
{
score++;
UpdateScoreText();
}
void UpdateScoreText()
{
if (scoreText != null)
{
scoreText.text = "Coins: " + score;
}
}
}
Save the script. Select the ScoreManager object and drag the ScoreText UI object from the Hierarchy into its Score Text field. Play the game and check the counter.
Part 9 — Troubleshooting
| Problem | Likely Cause | Suggested Fix |
|---|---|---|
| Player cannot move | Movement script not attached | Attach PlayerMovement to Player |
| Coins do not disappear | Is Trigger is disabled | Enable Is Trigger on coin colliders |
| Trigger method does not run | Rigidbody2D missing | Verify Player has Rigidbody2D |
| One coin does not disappear | CoinCollect script missing | Attach it to that coin |
| Score remains zero | ScoreManager absent or inactive | Add/enable ScoreManager object |
| NullReferenceException | ScoreManager instance unavailable | Ensure one active ScoreManager exists |
| Player cannot collect coins | Incorrect tag | Assign Player tag to Player |
| Input System errors | Input package/settings issue | Install and configure Input System |
Part 10 — Student Challenges
| Level | Challenge | Goal |
|---|---|---|
| Easy | More Coins | Add 10 coins instead of 5 |
| Easy | Different Colors | Make visually distinct collectible coins |
| Medium | Point Values | Make certain coins worth 5 points |
| Medium | Sound Effects | Play a sound when a coin is collected |
| Medium | Win Condition | Display a message when all coins are collected |
| Advanced | Countdown Timer | Collect coins within 30 seconds |
| Advanced | Random Coins | Spawn coins at random positions |
Part 11 — Student Assessment
Choose one answer for each question, then click Check Answers to view your score and explanations.
Part 12 — Project Submission Checklist
Check each item when your project is ready to submit.
0 of 9 items complete.
Part 13 — Grading Rubric
| Category | Points |
|---|---|
| Unity scene and Player setup | 15 |
| Working Player movement | 15 |
| Five coins correctly configured | 15 |
| Trigger collision detection | 20 |
| Destroying collected coins | 15 |
| Functional score counter | 10 |
| Project organization and submission | 10 |
| Total | 100 |
Expected Final Result
Students should finish with a playable 2D game featuring a blue character who moves around the screen collecting gold coins. Each collected coin disappears and increases the score until all five are collected.
This lesson builds on earlier Unity lessons covering movement, Rigidbody2D, collision detection, and trigger zones.
Unity reference: OnTriggerEnter2D API documentation