x


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"));
    }

}
more ▼

asked Dec 09 '10 at 12:54 AM

David 18 gravatar image

David 18
11 3 3 6

Hm, I'm sure I saw this exact same mistake in another post recently. Is this from a tutorial?

Dec 09 '10 at 02:00 AM Jesse Anders
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Dec 09 '10 at 01:08 AM

Statement gravatar image

Statement ♦♦
20.1k 35 70 175

Easy and functional! :D

Apr 12 '11 at 08:24 AM FrHaYwOrKs
(comments are locked)
10|3000 characters needed characters left

function OnCollisionEnter(collision : Collision) { Destroy(gameObject); }

place this in the canonball prefab, and if the canonball collide with something, it will be deleted!

more ▼

answered Nov 01 '12 at 03:56 PM

Wiebren de Haan gravatar image

Wiebren de Haan
-14 3 3 4

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5054
x2482
x764

asked: Dec 09 '10 at 12:54 AM

Seen: 6036 times

Last Updated: Nov 01 '12 at 03:56 PM