how to do something based on how many game objects exist

Lets say for example, if a player has three farms placed in the scene, and gets 3 Food from each farm placed, per second. So the player should get 3 food per farm per second. Currently the prefabs of the buildings are being instantiated with this code:

 public void SetItem(GameObject obj)
{
	hasPlaced = false;
	currentBuilding = ((GameObject)Instantiate(obj)).transform;
	currentBuilding.name = currentBuilding.name.Replace("(Clone)", "").Trim();
	currentBuilding.gameObject.GetComponent<PlaceableBuilding>().isPlaced = true;
	placeableBuilding = currentBuilding.GetComponent<PlaceableBuilding>();
}

But now my pondering is how would I go about in another script getting the number of game objects that have been placed in the scene. This script instantiates a prefab at the point the player clicks the mouse. How would go about checking to see how many farms are in the scene, every frame, so that i can adjust the food per second that the player is receiving?

Tags are perfect for this!

Tag your prefab gameObject with a tag called “Farm” or something similar so you’ll remember it.

Next, make a public array at the top of your script. It should look something like this.

//Top of the script where you reference things.

public GameObject[] listOfFarms;

Now inside your SetItem function, put something like…

listOfFarms = GameObject.FindGameObjectsWithTag("Farm");

Now you have all of your farms inside an “array.”

Now from any script, you can check how many farms are in the array by doing something like…

float numberOfFarmsInScene = listOfFarms.Count;
Debug.Log("I have " + listOfFarms.Count + "farms in my scene.");

Good luck!

Wow. Thanks, I thought findgameobjects by tag was to be used when trying to get a reference to a component on a game object didnt think to use it to get just the game object LOL