I have been developing a space-shooter and not a good one at that and I’ve reached a small sticking point concerning the counting of child objects.
Now, what I have is a gameObect, and in it i have a number of child objects and each one contains a transform position for an enemy, to which the enemy is instantiated at runtime . Anyway, I wanted to know when the current formation has been shot to pieces ie all the gameObjects at those transforms have been “destroyed”.
So, I used this code
print("EnemyCount: "+ transform.childCount);
if (transform.childCount <= 0)
{
print ("And their allll dead");
}
And the child count remains at the same number throughout even after all the enemies are destroyed. I am pretty sure that’s because that the child positional element itself is not destroyed. So, how can I test that the gameObject has been destroyed and that I’ve reached zero enemies in the formation.
To anyone who can help here is a big thankyou in advance!
One way would be to add each spawned enemy to a list, and then check the list to see if all the entries are null (meaning all the objects in the list have been destroyed). Generally speaking null values are not desirable, and it would be best to remove them from the list before destroying them, and check the list’s Count to see how many remain alive.
@CelticKnight , I think you just want to count the total number of enemies during runtime , right ?
If thats the case , your approach is not very effective I would say, I would recommend that you give a tag to all enemies, like “Enemy”. Then during runTime , you can just do a check in Update , like :
You really don’t want to be calling a Find function every single frame, it’s extremely inefficient as it makes the engine crawl through your entire scene hierarchy for game objects. That list will rarely change, so you’ll constantly be rebuilding that identical list every frame.
Yes, you are right of course, but, with this project their aren’t that many items in the hierarchy and I need some options to get to where I want this project to go. So I’ll first get it working and then explore other options and perhaps another question to the forum .
After thinking about it I don’t think I would need to do this every frame either. Just once after start up to get the number of enemies then save that variable as say a static variable and there and as they are destroyed take one away from this variable and when it equals zero then all the enemies have been destroyed! See you just need to do it once :).