- Home /
How to add values that are in a Text array?
How can i do it?
Im trying
public void AddValues()
{
for(int i = 0; i < valuesText.Length; i ++)
{
int.TryParse(valuesText[i].text, out totalResult);
int total = totalResult;
totalText.text = total.ToString();
}
}
Comment
Best Answer
Answer by joemane22 · Mar 08, 2020 at 07:03 PM
Ok so you are pretty much doing it right except you are assigning instead of adding.
//declare total outside the loop so the state persist over loops
int total = 0;
for(int i = 0; i < valuesText.Length; i ++)
{
//check to see if the parse was successfully to prevent runtime exceptions
if(int.TryParse(valuesText[i].text, out totalResult))
{
//add instead of asigning
total += totalResult;
}
}
//once finished, convert the sum to a string and assign it.
totalText.text = total.ToString();