ray an
ray an

Reputation: 1288

Why is OnCollisionEnter getting called twice?

I have got a Cube(player) and a Plane(floor) in my Scene. Both have Colliders attached to them and there is a RigidBody component attached only to the Cube. Cube is positioned above the Plane.

Cube has a script attached to it which looks for Collisions.

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

PROBLEM:

When the Plane and the Cube collides, the message gets printed twice.

...........................Collision

UnityEngine.Debug:Log(Object) jump:OnCollisionEnter(Collision) (at Assets/jump.cs:34)

...........................Collision

UnityEngine.Debug:Log(Object) jump:OnCollisionEnter(Collision) (at Assets/jump.cs:34)

Why is this happening? Is collision happening twice?

Upvotes: 2

Views: 14996

Answers (2)

cakar
cakar

Reputation: 71

I think it might be about the mesh collider. I had the same problem and when I changed the mesh collider to a box collider, the problem disappeared. My guess for the cause of this is the multiple collision lines within the mesh collider. Give it a try.

Upvotes: 1

Programmer
Programmer

Reputation: 125275

First of all, both logs seems to be coming from the jump.cs script at line 34 so we can safely say that the problem is just from one script not from many scripts.

Why is this happening?

Here are the possible reasons:

1.Your script with the OnCollisionEnter function is attached to multiple GameObjects. Those multiple GameObject's are the two GameObject's that are colliding with one another. When they collide, OnCollisionEnter is called multiple times.

enter image description here

2.Your script with the OnCollisionEnter function is attached to the-same GameObject multiple times.

enter image description here

3.Both Colliding GameObjects are colliding, exiting then colliding again. This is possible but not likely in this case but it is worth mentioning it.

You can verify this by adding OnCollisionExit too:

void OnCollisionExit(Collision collisionInfo) 
{
        print("Collision Out: " + gameObject.name);
}

Then check which order the logs are printed with the OnCollisionEnter function.

4.You have more than one colliders on each GameObject that are currently colliding. If you need to use multiple colliders as a compound collider, add them to a child empty GameObject then put them in a different tag so that you can ignore them from script.

enter image description here


Is collision happening twice?

Only you can answer this since the scene is in front of you.

Replace:

Debug.Log("...........................Collision");

with

Debug.Log("Collision: " + gameObject.name);

If the name of the GameObjects in both log are the-same then yes, it is likely happening twice.

Upvotes: 9

Related Questions