0
0
Unityframework~15 mins

OnCollisionEnter2D and OnTriggerEnter2D in Unity - Deep Dive

Choose your learning style9 modes available
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.