Array resets all values to 0, except the final value

I am reading various values from a text file, using the Parse function to convert each line into a float from a string, but whenever I try to sum the values up, or print all the values in the “val_list”, “sum” is equal to the last value in the list, and every value printed is equal to 0 APART FROM said last value. I am fairly new to C# and Unity so I may have missed some rule or something about arrays. Does anyone have any tips on how to solve my problem?

public void AcceptClick()
{
var textFile = Application.streamingAssetsPath + “/Val_Store/” + “Vals” + “.txt”;

int count = 0;
using (StreamReader reader = File.OpenText(textFile))
{
while (reader.ReadLine() != null)
{
count++; //value for determining how many indexes the array is going to have
}
}

string[ ] lines = File.ReadAllLines(textFile, Encoding.UTF8);
float[ ] val_list = new float[count];

foreach (string line in lines)
{
float temp = 0;
int count_str = 0;
temp = float.Parse(line);
val_list[count_str] = temp;
print(val_list[count_str]); //this prints every value in the text file as they come perfectly
count_str++;

}
float sum = 0;
foreach (float n in val_list)
{
print(n); // this will print (n-1) '0’s for n items in a list, with the nth value being actually what it should be
sum += n;
}
print(sum);
}

If I need to upload the project files, ask and I will asap

Move this line outside of your for each loop. You’re resetting it to zero inside the loop each time so you’re just writing to the 0th array index every time (overwriting the previous value each time)

2 Likes

I cannot state how stupid I feel now, thanks for stating what was not obvious to me :smile: