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.
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With