Bird
Raised Fist0
Unityframework~15 mins

OnCollisionEnter2D and OnTriggerEnter2D in Unity - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - OnCollisionEnter2D and OnTriggerEnter2D
What is it?
OnCollisionEnter2D and OnTriggerEnter2D are special functions in Unity used to detect when two 2D objects touch or overlap. OnCollisionEnter2D is called when two objects with physical colliders bump into each other, while OnTriggerEnter2D is called when an object enters a special area called a trigger. These functions help games respond to interactions like hitting walls or picking up items.
Why it matters
Without these functions, games would not know when objects touch or overlap, making it impossible to create interactive worlds. For example, characters wouldn't detect walls to stop moving, or players couldn't collect coins. These functions solve the problem of detecting physical contact and trigger zones easily and efficiently.
Where it fits
Before learning these, you should understand Unity basics like GameObjects, Components, and Rigidbody2D. After mastering these functions, you can learn about advanced physics interactions, event-driven programming, and optimizing collision detection for performance.
Mental Model
Core Idea
OnCollisionEnter2D and OnTriggerEnter2D are Unity’s way of telling your game when two 2D objects physically touch or overlap so you can react to those moments.
Think of it like...
Imagine two people bumping into each other in a room (collision) versus someone walking into a marked area like a doorway or a shop entrance (trigger). The bump is a physical contact, while the doorway is a special zone that notices when someone enters.
┌───────────────┐       ┌───────────────┐
│   Object A    │──────▶│ OnCollision   │
│ (with Collider│       │ Enter 2D      │
│ and Rigidbody)│       └───────────────┘
└───────────────┘
        │
        │
        ▼
┌───────────────┐       ┌───────────────┐
│   Object B    │──────▶│ OnTrigger     │
│ (with Collider│       │ Enter 2D      │
│ and IsTrigger)│       └───────────────┘
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding 2D Colliders and Rigidbody2D
🤔
Concept: Learn what 2D colliders and Rigidbody2D components are and how they enable physics interactions in Unity.
In Unity, a Collider2D is a shape attached to a GameObject that defines its physical boundaries for collisions. Rigidbody2D makes the object respond to physics like gravity and forces. Without Rigidbody2D, colliders only detect overlaps but don't cause physical reactions.
Result
You can create objects that can bump into each other or detect overlaps in a 2D space.
Understanding colliders and Rigidbody2D is essential because OnCollisionEnter2D only works when Rigidbody2D is involved, while triggers rely on collider settings.
2
FoundationDifference Between Collision and Trigger
🤔
Concept: Learn how colliders can be set as normal or triggers and what that means for interaction detection.
A normal collider blocks other colliders and causes physical collisions. A trigger collider does not block but detects when other colliders enter or exit its area. You set this by checking the 'Is Trigger' box on the collider component.
Result
You know when to use OnCollisionEnter2D for physical hits and OnTriggerEnter2D for detecting entry into zones without blocking movement.
Knowing this difference helps you choose the right method to detect interactions depending on whether you want physical response or just detection.
3
IntermediateUsing OnCollisionEnter2D for Physical Contacts
🤔Before reading on: do you think OnCollisionEnter2D is called when objects just overlap or only when they physically collide? Commit to your answer.
Concept: OnCollisionEnter2D is called when objects with colliders physically collide where at least one has a Rigidbody2D and they react to forces.
To use OnCollisionEnter2D, attach a script to a GameObject with Rigidbody2D and Collider2D. When it bumps into another collider, Unity calls OnCollisionEnter2D and passes collision details like contact points and the other object.
Result
Your game can respond to physical hits, like stopping movement, playing sounds, or applying damage.
Understanding that OnCollisionEnter2D requires Rigidbody2D on at least one object prevents confusion about why collisions sometimes don't trigger.
4
IntermediateUsing OnTriggerEnter2D for Zone Detection
🤔Before reading on: do you think OnTriggerEnter2D requires Rigidbody2D on the trigger object or the entering object? Commit to your answer.
Concept: OnTriggerEnter2D is called when a collider marked as a trigger overlaps with another collider, usually with Rigidbody2D on the moving object.
Set a collider's 'Is Trigger' to true to make it a trigger zone. Attach a script with OnTriggerEnter2D to detect when objects enter this zone. The entering object usually has Rigidbody2D to generate trigger events.
Result
You can detect when objects enter special areas without blocking their movement, like pickups or checkpoints.
Knowing that triggers detect overlaps without physical collision helps design interactive zones that don't interfere with movement.
5
IntermediateCollision and Trigger Event Parameters
🤔Before reading on: do you think OnCollisionEnter2D and OnTriggerEnter2D receive the same type of parameter? Commit to your answer.
Concept: OnCollisionEnter2D receives a Collision2D object with detailed contact info, while OnTriggerEnter2D receives a Collider2D object representing the other collider.
In OnCollisionEnter2D(Collision2D collision), you get info like contact points, relative velocity, and the other collider. In OnTriggerEnter2D(Collider2D other), you get the collider that entered the trigger but no contact details.
Result
You can access different levels of detail depending on the event type to respond appropriately.
Understanding the difference in parameters helps you write correct code and use the right data for your game logic.
6
AdvancedCombining Collisions and Triggers in Gameplay
🤔Before reading on: do you think an object can have both collision and trigger events at the same time? Commit to your answer.
Concept: Objects can have multiple colliders, some set as triggers and others as normal colliders, allowing both types of events simultaneously.
For example, a player can have a collider for physical collisions and a trigger collider for detecting nearby pickups. Scripts can implement both OnCollisionEnter2D and OnTriggerEnter2D to handle different interactions cleanly.
Result
Your game can handle complex interactions like bumping into walls and entering special zones without conflict.
Knowing that colliders can be combined expands your design options and prevents mixing up event logic.
7
ExpertPerformance and Physics Settings Impact
🤔Before reading on: do you think all collisions and triggers always generate events regardless of physics settings? Commit to your answer.
Concept: Physics settings like collision layers, Rigidbody2D body types, and sleeping affect when and how collision and trigger events fire.
Unity uses collision layers to filter which objects interact. Rigidbody2D can be dynamic, kinematic, or static, affecting event generation. Sleeping rigidbodies don't generate events until woken. Misconfigured layers or body types can cause missed events.
Result
You can optimize performance and fix bugs by correctly setting physics layers and Rigidbody2D types.
Understanding how physics settings influence events prevents common bugs where collisions or triggers don't fire as expected.
Under the Hood
Unity’s 2D physics engine continuously checks the positions and shapes of Rigidbody2D and Collider2D components each frame. When two colliders overlap or collide, the engine calculates contact points and collision responses. For OnCollisionEnter2D, it detects physical collisions and calls the method with detailed collision info. For OnTriggerEnter2D, it detects overlaps with trigger colliders and calls the method with the overlapping collider. These calls happen during the physics update cycle before rendering.
Why designed this way?
This design separates physical collisions from trigger overlaps to give developers control over whether objects physically block each other or just detect presence. It balances performance and flexibility by only calculating detailed collision info when needed and allowing triggers to be lightweight detection zones. Earlier designs mixed these concepts, causing confusion and inefficiency.
┌─────────────────────────────┐
│ Unity Physics Engine (2D)   │
│                             │
│  ┌───────────────┐          │
│  │ Rigidbody2D   │          │
│  │ + Collider2D  │          │
│  └──────┬────────┘          │
│         │                   │
│  ┌──────▼────────┐          │
│  │ Collision     │◀─────────┤
│  │ Detection     │          │
│  └──────┬────────┘          │
│         │                   │
│  ┌──────▼────────┐          │
│  │ OnCollision   │          │
│  │ Enter2D Event │          │
│  └───────────────┘          │
│                             │
│  ┌───────────────┐          │
│  │ Trigger       │          │
│  │ Detection     │          │
│  └──────┬────────┘          │
│         │                   │
│  ┌──────▼────────┐          │
│  │ OnTrigger     │          │
│  │ Enter2D Event │          │
│  └───────────────┘          │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does OnCollisionEnter2D get called if only one object has a Rigidbody2D? Commit to yes or no.
Common Belief:OnCollisionEnter2D requires both objects to have Rigidbody2D components to be called.
Tap to reveal reality
Reality:OnCollisionEnter2D is called if at least one object has a Rigidbody2D and both have colliders.
Why it matters:Believing both need Rigidbody2D can cause confusion and bugs when collisions don't register as expected.
Quick: Does OnTriggerEnter2D require the trigger collider to have Rigidbody2D? Commit to yes or no.
Common Belief:The trigger collider must have a Rigidbody2D for OnTriggerEnter2D to fire.
Tap to reveal reality
Reality:Only one of the two colliding objects needs Rigidbody2D; the trigger collider can be static.
Why it matters:Misunderstanding this leads to triggers not firing and wasted debugging time.
Quick: Do OnCollisionEnter2D and OnTriggerEnter2D provide the same collision details? Commit to yes or no.
Common Belief:Both events provide detailed collision contact information.
Tap to reveal reality
Reality:OnCollisionEnter2D provides detailed collision info; OnTriggerEnter2D only provides the collider reference without contact points.
Why it matters:Expecting detailed info from triggers can cause errors or incomplete logic.
Quick: Can an object with only a collider but no Rigidbody2D move and cause OnCollisionEnter2D events? Commit to yes or no.
Common Belief:Objects without Rigidbody2D can move and cause collision events.
Tap to reveal reality
Reality:Objects without Rigidbody2D are static and do not move or generate OnCollisionEnter2D events when moved by code.
Why it matters:This misconception leads to confusion when scripted movement doesn't trigger collisions.
Expert Zone
1
OnCollisionEnter2D events can be missed if Rigidbody2D objects are set to 'Sleeping' state; waking them manually can fix this.
2
Multiple colliders on one GameObject can cause multiple collision or trigger events; managing them carefully avoids duplicate responses.
3
Collision layers and physics matrix settings can silently block collision or trigger events, causing hard-to-debug issues.
When NOT to use
Avoid using OnCollisionEnter2D or OnTriggerEnter2D for very frequent or numerous objects as it can hurt performance; instead, use physics queries like OverlapCircle or raycasts for optimized detection.
Production Patterns
In real games, OnTriggerEnter2D is often used for pickups, checkpoints, and area effects, while OnCollisionEnter2D handles physical impacts like damage or bounce. Developers combine both with layer masks and event systems to organize complex interactions cleanly.
Connections
Event-driven programming
OnCollisionEnter2D and OnTriggerEnter2D are examples of event callbacks triggered by physics events.
Understanding these Unity events helps grasp how event-driven systems notify code about changes, a pattern common in UI, networking, and hardware interrupts.
Finite State Machines (FSM)
Collision and trigger events often cause state changes in game objects managed by FSMs.
Knowing how physics events trigger state transitions clarifies how games manage complex behaviors like enemy AI or player states.
Sensor networks (engineering)
Trigger colliders act like sensors detecting presence without physical contact, similar to motion sensors in security systems.
Recognizing triggers as virtual sensors connects game design to real-world detection systems, enriching understanding of event detection.
Common Pitfalls
#1Collision events not firing because Rigidbody2D is missing.
Wrong approach:GameObject.AddComponent(); // No Rigidbody2D added // OnCollisionEnter2D never called
Correct approach:GameObject.AddComponent(); GameObject.AddComponent(); // OnCollisionEnter2D will be called on collision
Root cause:Collision events require at least one Rigidbody2D; without it, Unity treats the object as static and does not generate collision callbacks.
#2Trigger events not firing because 'Is Trigger' is unchecked.
Wrong approach:collider.isTrigger = false; // OnTriggerEnter2D never called
Correct approach:collider.isTrigger = true; // OnTriggerEnter2D called when overlapping
Root cause:Triggers must have 'Is Trigger' enabled to detect overlaps without physical collision.
#3Expecting OnTriggerEnter2D to provide collision contact points.
Wrong approach:void OnTriggerEnter2D(Collider2D other) { var contacts = other.contacts; // Error: no contacts in trigger }
Correct approach:void OnCollisionEnter2D(Collision2D collision) { var contacts = collision.contacts; // Access contact points here }
Root cause:Trigger events only provide collider info, not detailed collision data.
Key Takeaways
OnCollisionEnter2D detects physical collisions between Rigidbody2D objects with colliders, providing detailed contact info.
OnTriggerEnter2D detects when objects enter trigger zones without physical collision, useful for pickups and area detection.
At least one object must have Rigidbody2D for collision or trigger events to fire.
Collider settings like 'Is Trigger' and physics layers control whether collisions or triggers happen.
Understanding these events and their parameters is essential for creating interactive and responsive 2D games in Unity.

Practice

(1/5)
1. Which Unity method is called when two solid objects with Rigidbody2D and Collider2D components collide physically?
easy
A. OnTriggerEnter2D
B. OnCollisionEnter2D
C. OnCollisionExit2D
D. OnTriggerExit2D

Solution

  1. Step 1: Understand collision detection methods

    OnCollisionEnter2D is called when two solid objects collide physically, both having Rigidbody2D and Collider2D components without trigger enabled.
  2. Step 2: Differentiate triggers from collisions

    OnTriggerEnter2D is called when an object enters a trigger collider, which is a collider set as a trigger, not a solid collision.
  3. Final Answer:

    OnCollisionEnter2D -> Option B
  4. Quick Check:

    Physical collision = OnCollisionEnter2D [OK]
Hint: Solid collisions use OnCollisionEnter2D, triggers use OnTriggerEnter2D [OK]
Common Mistakes:
  • Confusing trigger events with collision events
  • Using OnTriggerEnter2D for solid collisions
  • Assuming OnCollisionEnter2D works with trigger colliders
2. Which of the following is the correct method signature for detecting trigger entry in a 2D Unity script?
easy
A. void OnTriggerEnter(Collider other)
B. void OnCollisionEnter2D(Collider2D other)
C. void OnTriggerEnter2D(Collider other)
D. void OnTriggerEnter2D(Collider2D other)

Solution

  1. Step 1: Identify correct method name and parameter type

    The method for trigger detection in 2D physics is OnTriggerEnter2D and it takes a Collider2D parameter.
  2. Step 2: Check parameter types and method names

    void OnTriggerEnter2D(Collider2D other) matches the exact signature: void OnTriggerEnter2D(Collider2D other). Other options have wrong parameter types or method names.
  3. Final Answer:

    void OnTriggerEnter2D(Collider2D other) -> Option D
  4. Quick Check:

    Trigger 2D method = OnTriggerEnter2D(Collider2D) [OK]
Hint: Use OnTriggerEnter2D with Collider2D parameter for 2D triggers [OK]
Common Mistakes:
  • Using 3D Collider instead of Collider2D
  • Mixing OnTriggerEnter with OnTriggerEnter2D
  • Wrong parameter type in method signature
3. What will happen when the following Unity script is attached to a GameObject with a Collider2D set as a trigger, and another Rigidbody2D object enters it?
void OnTriggerEnter2D(Collider2D other) {
    Debug.Log("Trigger entered by " + other.name);
}

void OnCollisionEnter2D(Collision2D collision) {
    Debug.Log("Collision with " + collision.gameObject.name);
}
medium
A. Logs "Trigger entered by [object name]" when the other object enters the trigger collider.
B. Logs "Collision with [object name]" when the other object enters the trigger collider.
C. Logs both messages when the other object enters the trigger collider.
D. No logs appear because the methods are incorrect.

Solution

  1. Step 1: Understand trigger vs collision behavior

    The OnTriggerEnter2D method is called when an object enters a trigger collider. Since the collider is set as a trigger, this method will run.
  2. Step 2: Check collision method call conditions

    OnCollisionEnter2D only runs on solid collisions, not triggers. So it will not be called here.
  3. Final Answer:

    Logs "Trigger entered by [object name]" when the other object enters the trigger collider. -> Option A
  4. Quick Check:

    Trigger collider entered = OnTriggerEnter2D logs [OK]
Hint: Trigger colliders call OnTriggerEnter2D, not OnCollisionEnter2D [OK]
Common Mistakes:
  • Expecting OnCollisionEnter2D to run on triggers
  • Assuming both methods run simultaneously
  • Confusing Collider and Collision parameter types
4. A developer wrote this code but the OnTriggerEnter2D method never runs when expected. What is the likely problem?
void OnTriggerEnter(Collider2D other) {
    Debug.Log("Entered trigger");
}
medium
A. The method must return a boolean value.
B. The parameter type should be Collider, not Collider2D.
C. The method name should be OnTriggerEnter2D, not OnTriggerEnter.
D. The method should be private, not public.

Solution

  1. Step 1: Check method name correctness

    The method for 2D trigger detection must be named exactly OnTriggerEnter2D. The code uses OnTriggerEnter, which is for 3D physics.
  2. Step 2: Confirm parameter type and method signature

    The parameter Collider2D is correct for 2D triggers, but the method name mismatch prevents Unity from calling it.
  3. Final Answer:

    The method name should be OnTriggerEnter2D, not OnTriggerEnter. -> Option C
  4. Quick Check:

    Correct method name = OnTriggerEnter2D [OK]
Hint: Use exact method names for 2D events: OnTriggerEnter2D [OK]
Common Mistakes:
  • Using 3D method names for 2D physics
  • Wrong parameter types
  • Expecting return values from event methods
5. You want to detect when a player touches a collectible item in a 2D game without blocking movement. Which setup and method should you use to detect the event correctly?
hard
A. Set the collectible's Collider2D as a trigger and use OnTriggerEnter2D in the player's script.
B. Set the collectible's Collider2D as non-trigger and use OnCollisionEnter2D in the player's script.
C. Set both player and collectible colliders as triggers and use OnCollisionEnter2D.
D. Use OnTriggerEnter with 3D colliders on both objects.

Solution

  1. Step 1: Choose collider settings for collectibles

    To allow the player to pass through collectibles without blocking, the collectible's Collider2D must be set as a trigger.
  2. Step 2: Select correct detection method

    Use OnTriggerEnter2D in the player's script to detect when the player enters the collectible's trigger collider.
  3. Final Answer:

    Set the collectible's Collider2D as a trigger and use OnTriggerEnter2D in the player's script. -> Option A
  4. Quick Check:

    Trigger collider + OnTriggerEnter2D = collectible detection [OK]
Hint: Use triggers for collectibles to avoid blocking player movement [OK]
Common Mistakes:
  • Using solid colliders causing player to stop
  • Using OnCollisionEnter2D with triggers
  • Mixing 3D and 2D physics components