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;*