Need a script to count instances

I have a prefab of an asteroid and a script that creates instances at game start. I want to have a counter (OnGUI) that shows how many remain as I destroy them one by one with my badass lasers…

function OnGUI () {
GUI.Label (Rect (10,10,60,30), "Rocks left " + WHAT GOES HERE?);
}

I have tried all the FindObject(s) but can’t find a way for it to tell me how many remain…? Also trying to figure out the right way to “count” how many times a button has been pressed. Thanks!

You could have a variable that increments and decrements each time an asteroid instance is created or destroyed, respectively.

I can think of other ways, but that is probably the easiest way :slight_smile:

If the rocks have a script unique to them, use:

FindObjectsOfType(RockScript).length

add a static variable called instanceCount to the asteroid class and increment it in the awake function of the asteroid class and decrement it in OnDisable

OK, still new to scripting so an example would be great.

I Tried
FindObjectsOfType(rockcollision).length

and i get MissingFieldException: Field ‘rockcollision[ ].length’ not found.

^BUMP

Surely someone can help me further… FindObjects seems like the easiest way to do this, but it is giving me a hard time to say the least. I am sure its something simple I am missing. The scripting guide isn’t much help as it’s examples are too open ended.

Why isn’t there a FindObjectsOfName…?

Sounds easy but I am lost on how to do it. Some exapmle code would be excellent. Thanks!

Try using Length instead of length. It’s case sensitive.

-Jon

Also i think if there are none, it will return null as opposed to an empty array - so you might want to store it and check for that.

blarg = FindObjectsOfType(Foo);
if (blarg != null) print(blarg.length);

Length worked great. I spawn the asteroids from a script at game start. So now it counts how many there are, when i destroy one it decrements, when there are none left it shows 0. Thanks a million!

If you’re putting FindObjectsOfType in the OnGUI function, then its called every frame, which may not be optimal if you have a large number of GO’s.

It might be better to use an event to push this value when a relevant condition changes, rather than pull it every frame.