0
0
Unityframework~30 mins

OnCollisionEnter2D and OnTriggerEnter2D in Unity - Mini Project: Build & Apply

Choose your learning style9 modes available
Detecting Collisions and Triggers in Unity 2D
📖 Scenario: You are making a simple 2D game in Unity where a player can bump into walls and collect coins. You want to detect when the player hits a wall and when the player collects a coin.
🎯 Goal: Build a Unity C# script that uses OnCollisionEnter2D to detect hitting walls and OnTriggerEnter2D to detect collecting coins.
📋 What You'll Learn
Create a C# script with a OnCollisionEnter2D method that detects collisions with walls
Create a OnTriggerEnter2D method that detects triggers with coins
Use CompareTag to check if the collided object is a wall or a coin
Print messages to the console when collisions or triggers happen
💡 Why This Matters
🌍 Real World
Collision and trigger detection is essential in games to respond to player interactions with the environment and objects.
💼 Career
Game developers use these Unity methods daily to create interactive and responsive gameplay experiences.
Progress0 / 4 steps
1
Create the PlayerCollision script with empty methods
Create a C# script called PlayerCollision with empty methods OnCollisionEnter2D and OnTriggerEnter2D that take a parameter Collision2D collision and Collider2D other respectively.
Unity
Need a hint?

Start by writing a public class named PlayerCollision. Inside it, add two methods: OnCollisionEnter2D with a Collision2D parameter and OnTriggerEnter2D with a Collider2D parameter. Leave the methods empty for now.

2
Add tag checks for walls and coins
Inside OnCollisionEnter2D, add an if statement that checks if collision.gameObject.CompareTag("Wall"). Inside OnTriggerEnter2D, add an if statement that checks if other.gameObject.CompareTag("Coin").
Unity
Need a hint?

Use CompareTag on the gameObject inside the collision or trigger parameter to check if it matches "Wall" or "Coin".

3
Add print statements inside the tag checks
Inside the if block for walls in OnCollisionEnter2D, add Debug.Log("Player hit a wall!"). Inside the if block for coins in OnTriggerEnter2D, add Debug.Log("Player collected a coin!").
Unity
Need a hint?

Use Debug.Log inside each if block to print the messages exactly as shown.

4
Test the script by printing messages on collision and trigger
Run the game and make sure when the player hits a wall, the console shows Player hit a wall! and when the player collects a coin, the console shows Player collected a coin!. Write Debug.Log statements as in the script and confirm the output.
Unity
Need a hint?

Make sure your Unity console shows the exact messages when collisions and triggers happen.