How to sum all variables in scripts attached to all objects with a tag

I have multiple game objects with the tag “Hero” and each object with the Hero tag has a HeroStats script attached.

Each HeroStats script has a heroMaxHP variable.

How can I get the sum of all heroMaxHP variables from all objects with the “Hero” tag in my separate GameManager script?

Just have your GameManager keep a reference of all HeroStats and total it up whenever.

1 Like

The number of objects with the “Hero” tag is not static. I’m not certain what to use to grab everything. I can create an array of all the heroes using GameObject.FindGameObjectsWithTag(“Hero”) but then I don’t know how to access the variables of each object within that array. Is there a way to access those variables within the objects in the array, or is there a better way to access the variables directly?

When they’re created, have them access your GameManager (which should be a singleton), and have them subscribe to a List. Then, later on when you want to find all HeroStats, your GameManager already has a List of them.

1 Like