0
0
UnityHow-ToBeginner ยท 3 min read

How to Use OnCollisionEnter in Unity: Simple Collision Detection

In Unity, use the OnCollisionEnter method inside a script attached to a GameObject with a Collider and Rigidbody to detect collisions. This method is called automatically by Unity when the GameObject collides with another Collider during gameplay.
๐Ÿ“

Syntax

The OnCollisionEnter method has this syntax:

  • void OnCollisionEnter(Collision collision): Unity calls this method when the GameObject's Collider hits another Collider.
  • Collision collision: This parameter contains information about the collision, like the other object involved.
csharp
void OnCollisionEnter(Collision collision) {
    // Code to run when collision happens
}
๐Ÿ’ป

Example

This example shows a script that prints the name of the object it collides with. Attach this script to a GameObject with a Rigidbody and Collider to see it work.

csharp
using UnityEngine;

public class CollisionDetector : MonoBehaviour {
    void OnCollisionEnter(Collision collision) {
        Debug.Log("Collided with " + collision.gameObject.name);
    }
}
Output
Console output when collision occurs: "Collided with [OtherObjectName]"
โš ๏ธ

Common Pitfalls

  • Missing Rigidbody: OnCollisionEnter only works if at least one object has a Rigidbody component.
  • Collider setup: Both objects must have Colliders, and they must not be set as triggers.
  • Method signature: The method must be spelled exactly OnCollisionEnter with the correct parameter to be called by Unity.
csharp
/* Wrong: Missing Rigidbody, so no collision detected */
void OnCollisionEnter(Collision collision) {
    Debug.Log("Collision detected");
}

/* Right: Ensure Rigidbody is attached to this GameObject */
๐Ÿ“Š

Quick Reference

  • Attach script with OnCollisionEnter to a GameObject with Collider and Rigidbody.
  • Use collision.gameObject to access the other object involved.
  • Do not use IsTrigger on Colliders if you want OnCollisionEnter to fire (use OnTriggerEnter instead).
โœ…

Key Takeaways

OnCollisionEnter detects collisions when a GameObject with Rigidbody and Collider hits another Collider.
The method must have the exact signature: void OnCollisionEnter(Collision collision).
At least one object involved in the collision must have a Rigidbody component.
Colliders must not be set as triggers for OnCollisionEnter to work.
Use collision.gameObject to get information about the other object in the collision.