Let’s say I want to destroy all enemies at once. One thing I can do is use GameObject.FindGameObjectsWithTag, then run through the returning array and Destroy each returned gameObject.
That’s the better way to do it? There’s something else? SendMessage has nothing to do with this?
Update (2021-02-09):This answer is quite unsophisticated. It is correct only in regards to the question and should not be considered a general solution. Please read through the comment section as well.
I suppose you have an Enemy script?
To be sure to get any enemy destroyed you could declare a static generic List myEnemies.
(needs System.Generic… something along those lines, you will see it via code completion, there also is a tutorial about that in the scripting section).
Then you would implement a static function within your class which you would call for example RemoveAllEnemies
static void RemoveAllEnemies()
{
foreach(GameObject go in myEnemies)
{
myEnemies.Remove(go); // else there will be pointer to null
GameObject.Destroy(go);
}
}
you would call this function like this: Enemy.RemoveAllEnemies();
A static function only exists within the class, not the instantiated objects. to access the function it has to be public… i think.
I should also mention that you would need to actualy add the object to the list on creation of the object. best done in the awake() function.
May I suggest one simple solution? Not tested though…
Put all the GameObjects as children of one GameObject (say, a ‘big’ object named EnemyHerd, and every Enemy is a child of the big one.)
Then, Destroy() the parent.
I’d avoid using GameObject.Find and its derivatives as much as possible and instead keep a list of enemies in some kind of manager class somewhere.
Other then that, if you want to destroy all enemies I don’t think there is a better way then looping through your list of enemy gameObjects and calling Destroy on all of them.
Here is what I have used iterating backwards (@BergOnTheJob I tried yours but I think iteration is going wrong because you use count and it seems to be checked each loop and it changes). Also need to minus 1 to convert count to item number in list.
int maxItemId = enemyList.Count-1;
for (int i = maxItemId ; i >= 0; i--)
{
GameObject go = enemyList*;*