- Home /
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?
Answer by Vivien_Lynn · Jul 13, 2021 at 04:32 PM
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();
@Vivien_Lynn and @Devster2020 Thank you both for your answers! They were both correct but unfortunately I can only accept one. I hope an upvote is an acceptable consolation prize @Devster2020. Thanks!
Answer by Devster2020 · Jul 13, 2021 at 04:18 PM
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();
}
Your answer
Follow this Question
Related Questions
Text UI is not being assigned 2 Answers
Multiple Rich Text Not Working 1 Answer
Selecting a part of string in input field 1 Answer
Remove the & at the end of concatenated string 0 Answers
Ui text to string ? 1 Answer