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:
OnCollisionEnteronly 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
OnCollisionEnterwith 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
OnCollisionEnterto a GameObject with Collider and Rigidbody. - Use
collision.gameObjectto access the other object involved. - Do not use
IsTriggeron Colliders if you wantOnCollisionEnterto fire (useOnTriggerEnterinstead).
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.