- Home /
Count objects with a certain tag and display number on GUI
Is there a way to count objects that has a certain tag then put the number on a GUI? for example if there was 5 enemies all with an enemy tag, is there a way to publish that on a GUI text and if one enemy dies the number on the GUI go's to 4 as well??
Answer by fafase · Oct 03, 2012 at 11:31 AM
var enemies : GameObject[];
enemies = GameObject.FindGameObjectsWithTag("Enemy");
var count = enemies.length;
BUT!!! That would mean you are constantly throwing all this and Find function are expensive since they need to go through all the object of the game.
Instead keep a static counter that is incresed when instantiating and decreased when destroying.
I have a static counter at the moment but the problem is when I restart the level from my gui menu the count doesn't reset, it keeps counting down into the negatives
You need to call the lines I showed in my answer in the start function. This way if count is static it will be set to the appropriate value when the scene gets loaded.So the proper step is:
-declare the static var maybe in a static class to make it cleaner.
-Call the function that count how many of them in the Start function in a script where you have most of your level logic.
-if you instantiate enemies at runtime add count++;
-add count--; next to the Destroy function of your enemies.
That should make it.
You need to reset your static counter manually at Start / Awake functions.
Your answer
