How to Detect 2D Collision in Unity: Simple Guide
In Unity, you detect 2D collisions by adding
Collider2D components to your objects and using the OnCollisionEnter2D method in a script attached to one of the objects. This method is called automatically when two colliders touch, letting you respond to the collision in code.Syntax
To detect 2D collisions, use the OnCollisionEnter2D method inside a MonoBehaviour script. This method receives a Collision2D parameter that contains information about the collision.
void OnCollisionEnter2D(Collision2D collision): Called when this object's collider starts touching another collider.collision.gameObject: The other object involved in the collision.
csharp
void OnCollisionEnter2D(Collision2D collision) { Debug.Log("Collided with " + collision.gameObject.name); }
Example
This example shows a simple script that prints a message when the object collides with another 2D object. Make sure both objects have Collider2D components and at least one has a Rigidbody2D.
csharp
using UnityEngine; public class CollisionDetector : MonoBehaviour { void OnCollisionEnter2D(Collision2D collision) { Debug.Log("Collision detected with " + collision.gameObject.name); } }
Output
Collision detected with Enemy
Common Pitfalls
- For
OnCollisionEnter2Dto work, at least one object must have aRigidbody2Dcomponent. - Both objects need
Collider2Dcomponents that are not set as triggers. - If you want to detect overlaps without physical collision, use
OnTriggerEnter2Dand set one collider as a trigger. - Remember to attach the script to the correct GameObject with the collider.
csharp
/* Wrong: No Rigidbody2D attached, so collision won't be detected */ // Attach Rigidbody2D to one object to fix /* Right: Rigidbody2D on one object and Collider2D on both */ void OnCollisionEnter2D(Collision2D collision) { Debug.Log("Collision detected"); }
Quick Reference
| Component/Method | Purpose |
|---|---|
| Collider2D | Defines the shape for collision detection on 2D objects |
| Rigidbody2D | Enables physics and movement, required for collision events |
| OnCollisionEnter2D | Called when two colliders collide physically |
| OnTriggerEnter2D | Called when a collider marked as trigger overlaps another collider |
Key Takeaways
Add Collider2D components to both objects to detect collisions.
Ensure at least one object has a Rigidbody2D for collision events to fire.
Use OnCollisionEnter2D method in a script to respond to collisions.
Set colliders as triggers and use OnTriggerEnter2D to detect overlaps without physics.
Attach your collision detection script to the GameObject with the collider.