number of gameObjects on scene into a Variable

Hello guys,

I have been trying to get a script to work, or rather create a working script that will simply find the number of certain gameObjects in a scene then pass that number onto a Variable.

I have tried a number of things but nothing so far is working. I am no pro of C# but I am learning fast!

There is not much point to it, but here is what I have tried!

	public float startTime;
	public string currentTime;
	public int buildings;

	void Start () {
		GameObject.FindGameObjectsWithTag ("building").Length
	}
	
	// Update is called once per frame
	void Update () {
		startTime -= Time.deltaTime;
		currentTime = string.Format ("{0:0.0}", startTime);
		if (startTime <= 0) {

						if (buildings <= 0) {
								Application.LoadLevel (0);
						}
						if (buildings >= 0 ) {
				Application.LoadLevel (1);
			}
			}
	}

	void OnGUI() {
		GUI.Button(new Rect (10,10,100,45), currentTime);
	}
} 

So It works as

Once the time runs out the script looks to see if all gameOjects have been destroyed, if it is true or false then it sends the player to a certain level.

The only issue I am having is getting the number of buildings in the scene into a variable

Thanks for any help guys!

buildings = GameObject.FindGameObjectsWithTag(“building”).Length

will get the number of objects tagged with “building”. just run that wherever you need an updated count, but if you’re concerned about performance, an option would be to count at the start and update as you add/remove buildings.

You could do it this way:

public GameObject[] buildings;

void Start() {
buildings = GameObject.FindGameObjectsWithTag("building");
}

and then get the current amount of “buildings” with this:

buildings.Length;