x


Iterating through and deleting gameObjects

Hi, I'm back. This time, I was wondering how to iterate through and delete gameObjects using JS. I'm using an invisible sphere as a target for a LookAt function. It's created when the user clicks. I'll not bore you with the details, but basically, I need to iterate through a list of gameObjects tagged "Target", and delete them. This is because every time I click, it creates a new target. When a unit gets there, the target is destroyed. However, if I click twice, the unit ignores the old target and goes to the new one. This means that there is a target the unit doesn't get to, and therefor isn't destroyed. After several minutes of gameplay, there are empty targets all over the place. This isn't good, and I sought to iterate through them and delete them one by one. However, I'm not sure how to do this. I tried several different codes cobbled together from a bunch of different sources, and spent a long time trying to get it to work. Not being successful, I decided to pick the brains of the gurus, and so posted my question here again. Unfortunately, I can't upvote an answer more than once, but I'm hoping even 10 rep is an incentive to answer... Thanks in advance!

Elliot Bonneville.

more ▼

asked Mar 29 '10 at 11:44 PM

e.bonneville gravatar image

e.bonneville
5.7k 100 116 165

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

http://unity3d.com/support/documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html

That'll return a GameObject array that you can then do something like (assuming C#)

GameObject[] objects = GameObject.FindGameObjectsWithTag( "Target" );
foreach( GameObject go in objects )
{
    Destroy( go );
}
more ▼

answered Mar 29 '10 at 11:52 PM

Tetrad gravatar image

Tetrad
7.2k 27 37 89

I'm doing JS. Can you do that in JS? I know some of the broad differences between JS and C#, but not enough to translate something like that. I'll try though. I didn't know you could just destroy a gameobject. Thanks a ton!

Mar 30 '10 at 12:02 AM e.bonneville

@elbon96: Yes, you can do that in JS. for (go in objects) Destroy (go)

Mar 30 '10 at 12:18 AM Eric5h5

Thanks a ton! Got it. in fact, I was placing my code in the wrong place. Thanks everyone!!

Mar 30 '10 at 12:30 AM e.bonneville
(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:

x1356
x762
x242
x154
x24

asked: Mar 29 '10 at 11:44 PM

Seen: 6889 times

Last Updated: Mar 30 '10 at 12:06 AM