Tracking gameObjects as variables

Okay so I am trying to create a script or add to a current one to track the amount of gameObjects remaining. I need this to be a static variable so I can call it from another script. Any ideas? I was thinking maybe creating the variable and calling the object with a tag. not sure if this is the best way to go about things. Please Help.

So, any object that needs to be tracked, should have a script, that just before its destruction, sends a message out to the static var, removing one value from it.

someScript.someObjectCount--;
Destroy(gameObject);

There’s a few ways to go about doing this. One way is to have a static integer variable stored in your script (probably your player?). You would set the value at the start when you create your game objects. Then when your game objects are destroyed, just reduce the integer variable by 1.

Another way of doing it is to populate a list of your game objects. So when one game object is ‘destroyed’, it’s removed from the list. When the list count hits 0, it means all your game objects have been destroyed.

So far I am working with a script tied to these gates. The number of gates is hard coded and each time a gate is destroyed then intGatesRemaining–;
What I want to do is get rid of the hard coding.
intGatesRemaining is a static variable and is called from the score keeping script as well.
The problem I am also foreseeing is a 2nd level and the gates in that scene, or would that not matter?

Thats what I have going so far. I just have multiple instances of the same object and I am trying to get away from hard coding them.

What do you mean by ‘hard coded’?

Honestly, if you need to access the variable in another scene like for scoring, you would use a static variable. If you’re just using it to keep track of win/lose per scene, I don’t think you need to use a static variable at all.

You can always reset the value of the static var on a new level.

intGatesRemaing : int=8
So hard coded as having the number set to 8. The variable is just accessed in each scene by how many gates are left. I’m sorry I kind of get ahead of myself. First, I am trying to figure out if there is a way to track the gates in the scene by calling them in the script.

intGatesRemaining == gameObject.tag== “Gates”;

Something like that I guess? And it seems like I could just turn the

static var intGatesRemaining : int = 8 to static var intGatesRemaining : int;

if I can track the number of objects in the scene.

Thanks for the responses!

What you can do is in Start, you would call FindGameObjectsWithTag. Make sure you tag the gameobjects you want. Then it’ll return a gameobject array. Call .Length to get the size and set your variable.

C#

void Start()
{
intGatesRemaining = GameObject.FindGameObjectsWithTag("Gates").Length;
}

Oh awesome. Thank you so much!!