Get number of objects with a tag and have a bool script?

I am trying to get the number of objects tagged as enemies that are also archers. Archers are set by a bool on a script on the game object. How would I do this?

int UnitCountArcherEnemy = GameObject.FindGameObjectsWithTag(“Enemy”).Length; (only count the objects that have GetComponent().archer set to true)

int archerCount = 0;
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach (GameObject enemy in enemies)
{
  if (enemy.GetComponent<UnitClass>().archer) archerCount++;
}
Debug.Log("There were " + archerCount + " archers found.");
1 Like

awesome! thanks so much!

1 Like

An interface sounds like it would be useful here.
Whichever enemies you have that are supposed to be archers, you could give them an IArcher interface that contains archer-specific properties.

Then you’d only need to do this to find the number of archers in the scene:

FindObjectsOfType<IArcher>().Length;

Same could be done with different types of enemies as well.

1 Like

Thanks! I will look into this!