Unity 2D Game Development · Lesson 11

Collect the Coins

Build a playable 2D coin-collection game using movement, triggers, tags, the Destroy() method, and a score counter.

Beginner / Easy60–90 minutesUnity 2D + C#Student Lesson & Assessment

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

  1. Create collectible objects from 2D sprites.
  2. Add and configure Collider2D components.
  3. Use OnTriggerEnter2D() to detect overlapping objects.
  4. Identify the Player using tags.
  5. Remove collectibles using Destroy().
  6. Track collected coins with a score manager.
  7. Test and debug a working game.

Part 1 — Create the Unity Project

Step 1: Create a New Project

  1. Launch Unity Hub and click New Project.
  2. Select a 2D template, such as 2D Core or Universal 2D.
  3. Name the project PX_CollectCoins_L11_lastname.
  4. Select C:\UnityProjects as the project location.
  5. Click Create Project.

Step 2: Save the Scene

  1. Choose File → Save As or Save Scene As.
  2. Save the scene as CoinCollectorScene in Assets/Scenes.

Part 2 — Create the Player

Step 3: Add a Player Sprite

  1. Right-click in the Hierarchy and choose 2D Object → Sprites → Square.
  2. Rename the object Player.
  3. Set Position to (0, 0, 0) and Scale to (0.8, 0.8, 1).
  4. In Sprite Renderer, set its color to blue.

Step 4: Configure Physics

  1. Select Player and click Add Component.
  2. Add a Box Collider 2D.
  3. Add a Rigidbody 2D.
  4. Use the following settings:
Property Value
Body Type Kinematic
Gravity Scale 0
Simulated Enabled

Step 5: Assign the Player Tag

  1. Select Player.
  2. In the Inspector, open the Tag drop-down.
  3. Choose the built-in Player tag.

Part 3 — Program Player Movement

Step 6: Create the Script

  1. Create an Assets/Scripts folder.
  2. Inside it, create a MonoBehaviour C# script called PlayerMovement.
  3. 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

  1. Save the script and return to Unity.
  2. Drag PlayerMovement.cs onto the Player in the Inspector.
  3. Set Move Speed to 5.
  4. Press Play and test using WASD and arrow keys.
Teacher note: This script uses Unity's newer Input System. Make sure the Input System package is installed and enabled. For this beginner lesson, Transform-based movement is sufficient to demonstrate collectible triggers. A later physics lesson can use Rigidbody2D.MovePosition for physics-driven movement.

Part 4 — Create the Coins

Step 8: Create the First Coin

  1. Right-click in the Hierarchy and choose 2D Object → Sprites → Circle.
  2. Rename it Coin.
  3. Change Sprite Renderer color to yellow or gold.
  4. Set Scale to (0.5, 0.5, 1).
  5. Set Position to (2, 1, 0).

Step 9: Add a Trigger Collider

  1. Select Coin.
  2. Add a Circle Collider 2D component.
  3. 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

  1. Select the Coin and press Ctrl + D to duplicate it.
  2. Move each duplicate to a different location.
  3. 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

  1. Attach CoinCollect.cs to every coin.
  2. Press Play and move the Player toward a coin.
  3. Confirm that the coin disappears and the Console displays Coin Collected!.
  4. Collect the remaining coins.
Expected the Player stays visible and other coins remain until collected.

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

  1. Right-click in the Hierarchy and select Create Empty.
  2. Rename the new object ScoreManager.
  3. Attach ScoreManager.cs to 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

  1. Press Play.
  2. Collect all five coins.
  3. 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

  1. Choose UI → Text - TextMeshPro in the Hierarchy.
  2. Import TMP Essentials if prompted.
  3. Rename the text object ScoreText and position it in the top-left corner of the Canvas.
  4. Set its initial text to Coins: 0.
  5. Replace ScoreManager.cs with 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.

1. What is the purpose of Is Trigger on a coin's collider?
2. Which C# method responds to a 2D trigger entry?
3. What does CompareTag("Player") check?
4. What does Destroy(gameObject) do in CoinCollect.cs?
5. What happens when score++ runs?

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