- Home /
How do I count how many instances of a prefab there are?
Really basic question, but just not obvious to me: how can I find out how many of something there are in the whole level?
It's a predator/prey/competitor population sort of situation, where all the prefab instances keep getting born and dying all the time, and what happens to any individual depends on how many of its own kind there are, as well as how many of one or more others.
So I also want to know what the best, simplest, most flexible way is to do this. Should it be a script on one global thingcounter/healthupdater object doing an InvokeRepeating every so often? Or is actually counting them something to be avoided altogether, and instead make a variable and just make sure it goes up by one every time a new one is born and down by one every time one dies?
Answer by kylebarker82 · Jun 27, 2015 at 07:11 AM
void Update () {
GameObject[] thingyToFind = GameObject.FindGameObjectsWithTag ("ThingyToFind");
int thingyCount = thingyToFind.Length;
}
Worked nicely, needed to count the number of bullet impact prefabs that were cloned and delete the ones that went over board. Cheers
Answer by Julian-Glenn · Aug 14, 2010 at 03:22 AM
I would use your second solution myself. A static variable the increments and decrements would be sufficient and efficient I think.
Answer by Totalywicked · Nov 03, 2011 at 09:56 PM
you can set tags and then use GameObject.FindGameObjectsWithTag()
Your answer
Follow this Question
Related Questions
How do I get the count of children in a prefab? 1 Answer
Affect All Instances Of A Prefab 3 Answers
How to remove a specific instance of a prefab from List? 1 Answer
Gameobject missing camera when instance prefab 3 Answers
How can I link a GameObject instance to a script variable in a Prefab using the editor? 1 Answer