0
0
UnityHow-ToBeginner ยท 3 min read

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 OnCollisionEnter2D to work, at least one object must have a Rigidbody2D component.
  • Both objects need Collider2D components that are not set as triggers.
  • If you want to detect overlaps without physical collision, use OnTriggerEnter2D and 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/MethodPurpose
Collider2DDefines the shape for collision detection on 2D objects
Rigidbody2DEnables physics and movement, required for collision events
OnCollisionEnter2DCalled when two colliders collide physically
OnTriggerEnter2DCalled 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.