Add up updating float

I have a float that calculates the distance between 2 points, this updates at regular intervals showing the new distance.

I want to be able to add each new distance to the previous so I have a running total and display it as ui text.

I’ve found that if I use the following that it just adds the number consecutively rather than adding them together:

console.text += total_dist.ToString();

So I thought of creating a new float and adding the total_dist to that:

float cache_total = total_dist; 
cache_total += total_dist;

However, this doesn’t work either. It wont add to the cache_total but it changes at intervals much like the total_dist.

I’ve tired a couple of other different combinations such as setting the cache_total float to 0 first and switching round the totals so it’s this instead:

total_dist += cache_total;

but it always seems to overwrite the previous value.

How can I add the value each time it updates?

Hello @DJgray3D ,

Using “+=” on a string will append the value to the variable…

I hope I understand your request well…

So… if I understand what you want to do, you must have 2 variables … the first that keeps track of the total distances added up … and the second that keeps track only of the last distance.

So, what you should do is the following:

private float total_dist;

public void UpdateDistance(float lastDistance){
    this.total_dist += lastDistance;
    console.text = this.total_dist.ToString();

You create a variable float sum;

You keep adding what you want to add, like so:

sum += valueToAdd;

To Update your text, you write:
console.text = sum.ToString();