Menu
CoddyTech

OnCollisionEnter

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 8 of 63.

When two colliders start touching, Unity calls OnCollisionEnter(Collision collision) on the scripts of both objects. It is called once, on the physics step the touch begins, not again while they stay in contact. For a collision to happen at all, at least one of the two needs a Rigidbody that physics moves: a wall and a floor with no Rigidbody never report anything to each other.

This crate logs when it lands. It has a Rigidbody, so it falls, and the message arrives on the step it meets the floor:

void OnCollisionEnter(Collision collision)
{
    Debug.Log("Thud!");
}

The crate logs once, and again only after it leaves the floor and lands a second time. The floor gets the message too: a script on it would hear the crate land, even though the floor has no Rigidbody. The name and the parameter must be exact. A method named onCollisionEnter is never called, with no error. One that takes a Collider makes Unity log Script error: OnCollisionEnter with This message parameter has to be of type: Collision, and ignore it. While the two stay in contact Unity calls OnCollisionStay on every physics step, and when they part, OnCollisionExit once.

challenge icon

Challenge

Easy

The pressure plate counts what lands on it. The plate has no Rigidbody; the crate above it has one and falls onto it.

  • Each time something starts touching the plate, add 1 to a count and log it: Pressed 1, then Pressed 2 and so on.
  • Something resting on the plate counts once, however long it stays.

Press Play and watch the Console, then Check.

Try it yourself

using UnityEngine;

public class PressurePlate : MonoBehaviour
{
    // Count every landing and log it: Pressed 1, Pressed 2, ...
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay