Student lesson • Standalone HTML • No internet required for interactive activities
Unity 2D Game Development

Lesson 13: Timed Collection Game

Easy–Intermediate75–90 minutesUnity 2D + C#

Topics: Countdown timers, TextMeshPro, variables, conditional statements, game states.

Prerequisites: Lesson 11 — Collect the Coins; Lesson 12 — Add a Score.

Lesson Overview

Improve the existing Unity 2D coin-collection game by adding a 30-second countdown timer. Players must collect five coins before time runs out. Collecting all five coins displays YOU WIN!; reaching zero first displays TIME'S UP!. Movement and coin collection stop when the game ends.

COINS
0 / 5
TIME REMAINING
00:30

Interactive illustration: test the win and loss conditions using the buttons.

Learning Objectives

  1. Create a countdown timer using a floating-point variable.
  2. Explain Time.deltaTime and its role in frame-independent timing.
  3. Display the remaining time with TextMeshPro.
  4. Use conditional statements to detect the end of a game.
  5. Create and manage Playing, Won, and Lost game states.
  6. Stop movement and collection after the game ends.
  7. Show appropriate winning and losing messages.
  8. Test, debug, and submit the completed game.

Part 1 — Open the Previous Unity Project

Step 1: Open the Game

  1. Open Unity Hub.
  2. Open the PX_AddAScore_L12_lastname project.
  3. Save the project as PX_TimedCollection_L13_lastname
  4. Open CoinCollectorScene.
  5. Confirm it contains Player, at least five coins, ScoreManager, and GameCanvas.

Step 2: Save a New Scene

  1. Choose File → Save As / Save Scene As.
  2. Name the scene TimedCollectionScene.
  3. Save it in Assets/Scenes.

Step 3: Verify the Existing Game

Press Play. Confirm that movement works, coins disappear on contact, and the score increases. Stop Play Mode before editing.

Part 2 — Understand Countdown Timers

The countdown uses a float so it can track fractions of seconds.

public float startingTime = 30f;
private float timeRemaining;

Because Update() runs once per frame, subtracting a constant number each frame would give different timer speeds on different computers. Instead, subtract the time elapsed since the last frame:

timeRemaining -= Time.deltaTime;
Code / term Purpose
float Stores decimal values.
startingTime Initial countdown duration.
timeRemaining Time left in the game.
Update() Executes each frame.
Time.deltaTime Elapsed game time since the previous frame.
-= Subtracts and assigns the result.
Mathf.CeilToInt() Rounds up to a whole number for display.

Part 3 — Create the Timer Display

Step 4: Add TimerText

  1. Expand GameCanvas in the Hierarchy.
  2. Right-click it and choose UI → Text - TextMeshPro.
  3. If Unity requests it, import TMP Essentials.
  4. Rename the new text object TimerText.

Step 5: Configure TimerText

Setting Suggested Value
Text Time: 30
Font Size 36
Font Color White
Font Style Bold
Alignment Right
Anchor Top-right
Pos X / Pos Y -130 / -40
Width / Height 260 / 60

Position the timer opposite the score in the upper-right corner.

Part 4 — Create the GameTimer Script

Step 6: Create the Script

  1. Open Assets/Scripts.
  2. Create a new MonoBehaviour C# script named GameTimer.
  3. Open the script and enter the following code.

Step 7: Complete GameTimer.cs

using UnityEngine;
using TMPro;

public class GameTimer : MonoBehaviour
{
    public static GameTimer instance;

    public float startingTime = 30f;
    private float timeRemaining;

    public TMP_Text timerText;
    public TMP_Text messageText;

    public int coinsToWin = 5;

    public enum GameState
    {
        Playing,
        Won,
        Lost
    }

    public GameState currentState;

    public bool IsPlaying
    {
        get { return currentState == GameState.Playing; }
    }

    void Awake()
    {
        instance = this;
    }

    void Start()
    {
        timeRemaining = Mathf.Max(0f, startingTime);
        currentState = GameState.Playing;

        if (messageText != null)
        {
            messageText.text = "";
        }

        UpdateTimerDisplay();
    }

    void Update()
    {
        if (!IsPlaying)
        {
            return;
        }

        timeRemaining -= Time.deltaTime;

        if (timeRemaining <= 0f)
        {
            timeRemaining = 0f;
            GameOver();
        }

        UpdateTimerDisplay();
    }

    void UpdateTimerDisplay()
    {
        if (timerText != null)
        {
            int seconds = Mathf.CeilToInt(timeRemaining);
            timerText.text = "Time: " + seconds;
        }
    }

    public void CheckForWin(int currentScore)
    {
        if (!IsPlaying)
        {
            return;
        }

        if (currentScore >= coinsToWin)
        {
            currentState = GameState.Won;

            if (messageText != null)
            {
                messageText.text = "YOU WIN!";
            }

            Debug.Log("You Win!");
        }
    }

    void GameOver()
    {
        currentState = GameState.Lost;

        if (messageText != null)
        {
            messageText.text = "TIME'S UP!";
        }

        Debug.Log("Game Over!");
    }
}

Step 8: Attach GameTimer

  1. Save the script and return to Unity.
  2. Create an empty GameObject in the Hierarchy.
  3. Rename it GameTimer.
  4. Attach GameTimer.cs.
  5. Set Starting Time to 30 and Coins To Win to 5.
  6. Assign the Timer Text and Message Text references later in this lesson.
Important: Keep exactly one active ScoreManager from Lesson 12. GameTimer is an additional object, not a replacement for ScoreManager.

Part 5 — Understand the Timer Code

Decrease Remaining Time

timeRemaining -= Time.deltaTime;

End the Game at Zero

if (timeRemaining <= 0f)
{
    timeRemaining = 0f;
    GameOver();
}

Display Whole Seconds

int seconds = Mathf.CeilToInt(timeRemaining);
timerText.text = "Time: " + seconds;

The display changes from Time: 30 to Time: 29, eventually reaching Time: 0.

Game State Rules

State Meaning What the Player Can Do
Playing Time remains and the target has not been reached. Move and collect coins.
Won Required coins collected before time expires. Gameplay stops; YOU WIN appears.
Lost Time reaches zero first. Gameplay stops; TIME'S UP appears.

Part 6 — Create the Win/Lose Message

Step 9: Add MessageText

  1. Right-click GameCanvas.
  2. Choose UI → Text - TextMeshPro.
  3. Rename the element MessageText.
  4. Leave the initial text blank.

Step 10: Format MessageText

Setting Suggested Value
Anchor Center
Position X / Y 0 / 0
Width / Height 700 / 120
Font Size 64
Color Yellow
Alignment Center
Font Style Bold

Step 11: Assign References

  1. Select GameTimer in the Hierarchy.
  2. Drag TimerText into its Timer Text field.
  3. Drag MessageText into its Message Text field.
  4. Verify Starting Time = 30 and Coins To Win = 5.

Part 7 — Connect the Timer to Coin Collection

Step 12: Replace CoinCollect.cs

Use this version to award points, check for a win, and destroy the collected coin.

using UnityEngine;

public class CoinCollect : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
        if (!other.CompareTag("Player"))
        {
            return;
        }

        if (GameTimer.instance == null ||
            !GameTimer.instance.IsPlaying)
        {
            return;
        }

        if (ScoreManager.instance == null)
        {
            Debug.LogWarning("ScoreManager is missing!");
            return;
        }

        // Add one point to the score.
        ScoreManager.instance.AddCoin();

        // Check whether the player has won.
        GameTimer.instance.CheckForWin(
            ScoreManager.instance.score
        );

        // Remove the collected coin.
        Destroy(gameObject);
    }
}
How it works: The trigger checks for the Player tag, confirms the game is Playing, increases the score, checks the winning target, and destroys the coin. It uses the ScoreManager from Lesson 12, with score and AddCoin().

Part 8 — Stop Movement When the Game Ends

Step 13: Replace PlayerMovement.cs

The script below uses Unity's newer Input System. Its new game-state check stops movement after a win or loss.

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;

    void Update()
    {
        // Stop movement after the game ends.
        if (GameTimer.instance == null ||
            !GameTimer.instance.IsPlaying)
        {
            return;
        }

        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);
    }
}

This beginner script follows the earlier lessons' Transform-based movement approach. For a later physics-focused lesson, students can switch to Rigidbody2D movement.

Part 9 — Review the Scene Hierarchy

▾ TimedCollectionScene
▸ Player
▸ Coin 1 through Coin 5
▸ ScoreManager
▸ GameTimer
▾ GameCanvas
▸ ScoreText
▸ TimerText
▸ MessageText

Make sure all scripts are attached to the appropriate GameObjects and all text references are assigned in the Inspector.

Part 10 — Test the Timed Game

Step 14: Test Losing

  1. Press Play.
  2. Verify the timer begins at 30 seconds.
  3. Do not collect any coins.
  4. When the timer reaches zero, confirm TIME'S UP! appears.
  5. Try moving the Player. Movement should be disabled.

Step 15: Test Winning

  1. Stop Play Mode.
  2. Temporarily change Starting Time to 60 seconds.
  3. Press Play and collect all five coins.
  4. Verify YOU WIN! appears and movement stops.

Step 16: Restore the Game

Stop Play Mode, restore Starting Time to 30, and save the scene.

Test Event Expected Behavior
Game starts Time: 30, Score: 0
Collect one coin Score increases by one
Timer reaches ten seconds Time: 10 appears
Collect five coins YOU WIN!
Timer reaches zero first TIME'S UP!
Move after game ends No movement
Trigger after game ends No additional points

Part 11 — Troubleshooting

Problem Cause / Solution
Timer does not appear Assign TimerText to GameTimer.
Timer stays at 30 Check GameTimer is attached, enabled, and has no compilation errors.
Timer goes below zero Clamp to zero before GameOver in Update.
Game does not end at zero Verify GameOver() is called.
Win message missing Verify Coins To Win and CheckForWin().
NullReferenceException Check GameTimer, ScoreManager, and UI references.
Player cannot move at start Check GameTimer is active and initialization succeeds.
Coins are not collected Verify trigger collider, Player tag, Rigidbody2D, and CoinCollect.
TMP_Text not recognized Add using TMPro; and confirm TextMeshPro is installed.
Keyboard input errors Check the Input System package and project input settings.

Part 12 — Student Challenges

Difficulty Challenge Description
Easy Change Time Limit Try 15 seconds instead of 30.
Easy More Coins Add 10 coins and adjust Coins To Win.
Easy Timer Color Turn the countdown red during the last 10 seconds.
Medium Extra Time Add a special pickup that awards five seconds.
Medium Restart Button Let the player restart the scene.
Medium Win Screen Show the final score when the player wins.
Advanced Difficulty Settings Easy: 60 sec; Medium: 30 sec; Hard: 15 sec.
Advanced Best Time Track fastest successful completion.

Optional Challenge: RestartGame.cs

using UnityEngine;
using UnityEngine.SceneManagement;

public class RestartGame : MonoBehaviour
{
    public void Restart()
    {
        SceneManager.LoadScene(
            SceneManager.GetActiveScene().buildIndex
        );
    }
}
  1. Include the scene in the Build Profiles scene list (Build Settings in some Unity versions).
  2. Make an empty GameObject called RestartManager and attach the script.
  3. Add a UI Button to GameCanvas and label it Restart.
  4. In the Button's On Click event, assign RestartManager and choose RestartGame → Restart().

Part 13 — Student Assessment

Choose an answer for each question, then select Check Answers.

Part 14 — Project Submission Requirements

Check each requirement after confirming it in your Unity project.

0 of 11 complete

Part 15 — Grading Rubric

Category Points
Correct Unity scene setup 10
GameTimer script and variables 20
Countdown using Time.deltaTime 20
TextMeshPro timer display 15
Win and lose conditions 15
Stopping gameplay after game ends 10
Testing, debugging, and submission 10
Total 100

Expected Final Result

Students will have a playable Unity 2D game with a 30-second timer, score counter, coin collection, and clear win/lose conditions. They will understand time-based programming, variables, conditional statements, and game-state management.

This work prepares students for time limits, game-over screens, levels, and increasingly difficult games.