- Home /
How to sum a property of a class in a List
I'm using lists to be able to use more than one engine in my SpaceShip game. So, there is the engine Class that has variable ForceGenerated and FuelCapacity.
How I can be able to use List<>.Sum(all variable ForceGenerated) I don't know the syntax to use this Sum (I saw docs on Microsoft, but I still don't understand)
Answer by xortrox · May 02, 2014 at 04:57 PM
float totalForceGenerated = 0.0f;
float totalFuelCapacity = 0.0f;
foreach(NameOfEngineClass e in nameOfList)
{
totalForceGenerated += e.ForceGenerated;
totalFuelCapacity += e.FuelCapacity;
}
alternative using normal for:
float totalForceGenerated = 0.0f; float totalFuelCapacity = 0.0f; for(int i = 0; i < nameOfList.Count; i++) {
totalForceGenerated += nameOfList[i].ForceGenerated;
totalFuelCapacity += nameOfList[i].FuelCapacity;
}
Yes true... I've thought to do this but I'm a bit stupid (Lol). I didn't thought how to calculate it every frame that was a easy problem.
But none know the syntax of List.Sum(variables of the ListClass)?
I wouldn't use List.Sum. Not only is this a pretty simple thing to do with a loop but some platforms (like iOS) don't play nicely with those functions on a generic.
Yeah, but I've to check 2 different list to check with this method (2 loops + another that I use to "update" the current fuel) and it seems to me a heavy script, so I thought that maybe List.Sum was cheaper.
Is it correct?
P.s. If only iOS doesn't support it, isn't a problem...
Answer by jeebxoxo · May 02, 2014 at 05:01 PM
Just loop through your list and add them all in a variable.
public float totalForce;
// you probably already have this list elsewhere I'm just showing it so you see where I get 'engines'
public List<Engine> engines = new List<Engine>();
void AllForce () {
totalForce = 0.0f;
foreach(Engine e in engines) {
totalForce += e.ForceGenerated;
}
}
im trying to use something similar to this and watch it in the update. it keeps adding to it