- Home /
Trying to Delete Object upon Collision
I've tagged my Cannonball's prefab with 'CannonBall' and I made this function to delete them when they collide. I added it to the prefab as well. Problem is, they don't delete. Any mistake in my logic? I'm pretty new to Unity. Thanks!
function OnCollisionEnter(collision : Collision) { if (collision.gameObject.tag == "CannonBall") { Destroy(GameObject.FindWithTag("CannonBall")); }
}
Hm, I'm sure I saw this exact same mistake in another post recently. Is this from a tutorial?
Answer by Statement · Dec 09, 2010 at 01:08 AM
You already have the reference to the object you want to destroy so there is no need to attept to find it.
function OnCollisionEnter(collision : Collision)
{
if (collision.gameObject.tag == "CannonBall")
{
Destroy(collision.gameObject);
}
}
Other than that, make sure that your cannon ball has a collider and that the tag of that colliders game object really is exactly "CannonBall".
If you would use GameObject.FindWithTag you might get "any" cannonball. Maybe not the one you collided with.
Answer by Wiebren-de-Haan · Nov 01, 2012 at 03:56 PM
function OnCollisionEnter(collision : Collision) { Destroy(gameObject); }
place this in the canonball prefab, and if the canonball collide with something, it will be deleted!
Your answer
![](https://koobas.hobune.stream/wayback/20220613090327im_/https://answers.unity.com/themes/thub/images/avi.jpg)