- Home /
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.
Answer by Tetrad · Mar 29, 2010 at 11:52 PM
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 );
}
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!
@elbon96: Yes, you can do that in JS. for (go in objects) Destroy (go)
Thanks a ton! Got it. in fact, I was placing my code in the wrong place. Thanks everyone!!
Your answer
![](https://koobas.hobune.stream/wayback/20220612134657im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Why is iterating an array and destroying objects considered bad practice? 2 Answers
destroying a unit and removing it from a list 2 Answers
How to destroy all the items with one function? 2 Answers
How to destroy the first clone of a UI Image using an array every time I press a button? 1 Answer
Destroy Particle System in an Array 0 Answers