- Home /
How to let multiple values contribute two one value constantly
I'm working on a sending system in my game right now and I have an idea of how its going to work. This idea includes a value that holds and adds up multiple other values that are changing constantly and also sum those specific values up. The only problem is that I don't know how to make a value like that. At the moment the only things that comes to my mind is an array or list. An example would be this, There are multiple generators producing electricity. the amount of electricity is represented by a number and is being increased every second. I need something, be it an array, list ,variable , or something else, that contains the amount of electricity(the numbers) that all the generators are producing. That something also needs to be able to sum up all of the electricity that is produced.
Your question is not very clear, especially the would let me be able to reference specific values from it,
part. An example would help.
I have added an example, I realize I don't have to access specific values so just ignore that
Answer by DJT4NN3R · Jun 11, 2020 at 12:22 AM
You can use static variables and a get-only accessor to do all the math without having to re-write it each time.
class Generator
{
// keeps a list of all generator instances
static List<Generator> instances = new List<Generator>();
// the amount of energy this instance has
internal float electricity { get; set; }
// returns a float[] containing the energy each instance has
static float[] energyOfInstances
{
get
{
float[] value = new float[instances.Count];
for (int i = 0; i < instances.Count; i++)
value[i] = instances[i].energy;
return value;
}
}
// returns the total energy across all instances
static float totalEnergy
{
get
{
float value = 0;
foreach (Generator g in instances)
value += g.energy;
return value;
}
}
// constructor that adds the new instance to the list of instances. make sure you are also somehow removing the disposed instances from the list.
Generator()
{
instances.Add(this);
}
}
Then, if you want to know the amounts of electricity being produced by each indivudal generator:
float[] foo = Generator.energyOfInstances;
Then, whenever you want to know the total amount of electricity, you can just get the value of Generator.totalEnergy
, and all the math is done within the get
function.
float f = Generator.totalElectricity;
From a performance standpoint, however, this would be essentially the same as writing it out each time you need the value. If you're going to be querying these multiple times each frame, and the values won't be changing between queries, I suggest caching it (like I did in the example above) instead of using the static variable each time you want to know.