Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnCollisionEnter() not working in Unity3D

Tags:

c#

unity3d

I have an object with a mesh collider and a prefab with sphere collider. I want the instance of the prefab to be destroyed if the two collide.

I wrote the following in a script:

private void OnCollisionEnter(Collision c)
{
    if (c == target)
        Destroy(transform.gameObject);
    print("something");                   // Doesn't get printed
}

But it is not working. I have tried toggling isTrigger on both the objects.

like image 606
Temp Id Avatar asked Aug 16 '13 20:08

Temp Id


People also ask

Why isnt OnCollisionEnter working Unity?

If you want your OnCollisionEnter to be called make sure: (a) Both objects have a collider attached. (c) One of the objects (doesn't matter which of them) is a rigid, non kinematic & non static object (the second don't have to be a rigid body).

Why is my collider not working?

When it seems a collider is not working in your Unity scene, there are a few things that you might want to look at. Check if the colliders corresponding to the game objects are attached to their respective game objects. If one or both colliders are not attached, that's the first thing you should fix.

What is the difference between OnCollisionEnter and OnTriggerEnter?

The OnCollisionExit method closes out the object interaction by getting called as soon as the objects stop touching. An OnTriggerEnter collision is a pass through collision, where objects don't bounce off each other, but events can be triggered when contact is made.


2 Answers

Have a look at this table

If you want your OnCollisionEnter to be called make sure:

(a) Both objects have a collider attached.

(b) None of the objects is a trigger collider (this will issue OnTrigger function & not OnCollisionEnter)

(c) One of the objects (doesn't matter which of them) is a rigid, non kinematic & non static object (the second don't have to be a rigid body).

(d) Due to computational difficulties MeshCollider might have hard times colliding with other mesh collider, use them with caution.

(e) Make sure both the objects are in the same layer (or at least that they collide in scene settings).

(f) If you are working in 2d - OnCollisionEnter2D will be called, rename your function.

example colider configuration

like image 33
Ohad Cohen Avatar answered Oct 21 '22 16:10

Ohad Cohen


I had the same problem of OnCollisionEnter not being called and found this question.

For me, the problem was that I was making a 2D game so the answer is to use the OnCollisionEnter2D function instead.

like image 186
Peter de Rivaz Avatar answered Oct 21 '22 16:10

Peter de Rivaz