A counting script?

Greetings Unity friends! I have a scripting question for you today:

Is there a script that can count or number how many of a certain object there are in a scene?

Specifically, I’m working on a game where there are a certain number of goals in each scene. I want my script to count how many goal objects are in the scene, compare that to how many goals that the player has made and, when all goals have been accomplished, register a win.

I looked up “count” in the scripting reference and like a hundred different things came up and none of them seemed to match.

Any help would be greatly appreciated, even if someone could point me in the right direction.

Thanks!

Dwayne
The Chicken Reborn

1 Answer

1

Tag your goal objects as “Goal”, then:

var goals : GameObjects[] = GameObject.FindGameObjectsWithTag("Goal");
var goalCount : int = goals.length;

As you can see here, FindGameObjectsWithTag returns an array of GameObjects. Then, the length of the array is your number of goals…

Glad it did! Btw, you should comment and not reply in these cases. Accepting my answer would also help others to identify it as such!

Hello, I tried this script, but somehow got this error instead Assets/Script/PlayerController.cs(96,33): error CS1525: Unexpected symbol :', expecting )', ,', ;', [', or =' Any assistance? Thanks!

The script is in JavaScript, you are using C#. The appropriate C# script is as follows GameObjects[] goals = GameObject.FindGameObjectsWithTag("Goal"); int goalCount = goals.length;