Lesson 13: Timed Collection Game
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.
0 / 5
00:30
Interactive illustration: test the win and loss conditions using the buttons.
Learning Objectives
- Create a countdown timer using a floating-point variable.
- Explain
Time.deltaTimeand its role in frame-independent timing. - Display the remaining time with TextMeshPro.
- Use conditional statements to detect the end of a game.
- Create and manage Playing, Won, and Lost game states.
- Stop movement and collection after the game ends.
- Show appropriate winning and losing messages.
- Test, debug, and submit the completed game.
Part 1 — Open the Previous Unity Project
Step 1: Open the Game
- Open Unity Hub.
- Open the
PX_AddAScore_L12_lastnameproject. - Save the project as PX_TimedCollection_L13_lastname
- Open
CoinCollectorScene. - Confirm it contains Player, at least five coins, ScoreManager, and GameCanvas.
Step 2: Save a New Scene
- Choose File → Save As / Save Scene As.
- Name the scene
TimedCollectionScene. - 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
- Expand
GameCanvasin the Hierarchy. - Right-click it and choose UI → Text - TextMeshPro.
- If Unity requests it, import TMP Essentials.
- 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
- Open
Assets/Scripts. - Create a new MonoBehaviour C# script named
GameTimer. - 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
- Save the script and return to Unity.
- Create an empty GameObject in the Hierarchy.
- Rename it
GameTimer. - Attach
GameTimer.cs. - Set Starting Time to 30 and Coins To Win to 5.
- Assign the Timer Text and Message Text references later in this lesson.
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
- Right-click GameCanvas.
- Choose UI → Text - TextMeshPro.
- Rename the element
MessageText. - 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
- Select GameTimer in the Hierarchy.
- Drag
TimerTextinto its Timer Text field. - Drag
MessageTextinto its Message Text field. - 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);
}
}
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
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
- Press Play.
- Verify the timer begins at 30 seconds.
- Do not collect any coins.
- When the timer reaches zero, confirm TIME'S UP! appears.
- Try moving the Player. Movement should be disabled.
Step 15: Test Winning
- Stop Play Mode.
- Temporarily change Starting Time to 60 seconds.
- Press Play and collect all five coins.
- 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
);
}
}
- Include the scene in the Build Profiles scene list (Build Settings in some Unity versions).
- Make an empty GameObject called
RestartManagerand attach the script. - Add a UI Button to GameCanvas and label it Restart.
- 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
This work prepares students for time limits, game-over screens, levels, and increasingly difficult games.