Using foreach to grab values from multiple objects

Hi id like to use a foreach loop to grab the variable “health” from multiple objects and then combine them into one variable, Currently what ive got is as follows

void getMyStats()
	{
		foreach(GameObject card in GameObject.FindGameObjectsWithTag("PlayerOne"))
		{
			Get health value here from each card
		}
	}

thats as far as i’ve gotten and im not really sure were i should go from here, any help would be greatly appreciated.

If I wanted to get the sum of health for all Zombies in my scene, I’d probably use Linq for that (assuming it’s a float):

using System.Linq;
using System;
public float GetZombiesTotalHealth()
{
    Zombies[] zombies = GameObject.FindObjectsOfType(typeof(Zombie)) as Zombie[];    

    IEnumerable<float> healths =
        from z in zombies
        where z != null
        select z.Health;

    return healths.Sum();
}

And you always have the old school way of doing it:

public float GetZombiesTotalHealth()
{
    Zombies[] zombies = GameObject.FindObjectsOfType(typeof(Zombie)) as Zombie[];
  
    float totalHealth = 0;       
    for (int i = 0, len = zombies.Length; i < len; i++)
       totalHealth += zombies*.Health;*

return totalHealth;
}
([If you’re interested in learning LINQ][1])
[1]: C# LINQ - YouTube

Add this in the beginning of the class to be able to use the List type:

using System.Collections.Generic;

Then your code could go like this, to create a list of all the health values of all the objects tagged with “PlayerOne”:

void getMyStats()
{
	List<float> cardHealth = new List<float>();
	
	foreach(GameObject card in GameObject.FindGameObjectsWithTag("PlayerOne"))
	{
		cardHealth.add(card.health);
	}
}

then you could iterate over the health list and do what you please:

float totalHealth = 0;
foreach(float health in cardHealth)
{
    totalHealth += health; // for example sum up the health of all cards to one variable
}

Of coure you could also do that directly in your original foreach loop:

void getMyStats()
{
	float totalHealth = 0;
	foreach(GameObject card in GameObject.FindGameObjectsWithTag("PlayerOne"))
	{
		totalHealth += card.health;
	}
}