OnCollisionEnter() not firing when collision occurs

  • Both objects have a Rigidbody attached to them
  • Neither objects Rigidbody component are “Kinematic”
  • The two objects have box colliders attached, not mesh colliders
  • The script is being called from the object with the box collider attached
  • Both object layers are ticked in the Settings > Physics panel
  • Neither box colliders have “Trigger” set to true
  • The objects cannot pass through each other in world space
  • The code is attached to a prefab that is already instantiated in the world.

However, the following code does not execute:

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Entity")
    {
        hitDetected = true;
        collision.gameObject.GetComponent<EntityBehaviour>().isDead = true;
        GameObject.Find("PlayerController").GetComponent<ShipController>().AddScore(100);
    }
}

There is no “Collision!” appearing in the Debug log, and none of the code runs.

Unity 5 is not broken. What am I missing?

Np! I'm glad it helps :)

2 Answers

2

The message parameter has to be of type Collision, not Collider. Unity console should show you this error.

No error in console. Changed to "collision" as parameter and still not working.

Now you don't have Debug.log("Collision!") in your code. Anyway, the code you provided is working fine, error must be somewhere else. Are you spelling the name "OnCollisionEnter" correctly in the code? Are you using 3D physics or 2D physics (it would be OnCollisionEnter2D in that case) ? Isn't the rigidbody child of another rigidbody? Have you saved your code? Have you applied changes to the prefab?

Is the object tagged “Entity”. Just checking. Sometimes the smallest things slip thru the cracks.