- Home /
List Elements Double With Replicate Data
I currently have a leaderboard that saves scores from every run and sorts them accordingly, on the backend it is saving/loading and sorting them correctly. However, when I run the following SetScores(); on a click the list duplicate its self to 20 elements long. This keeps ending in out of bounds exceptions.
Edit: It adds 10elements on every button click.
public List<int> leaderboard= new List<int>();
public TextMeshProUGUI[] scores;
private void Start()
{
//This gets a full list of data; 10 elements
leaderboard= LeaderboardTracker.lt.GetScores();
}
public void SetScores()
{
int i = 0;
foreach (int item in leaderboard)
{
scores[i].text = item.ToString();
i++;
}
}
How do you ensure that your scores
length equals to leaderboard.Length
?
are you sure to int i
is a local variable, maybe changing name
int ensuredThatIsLocal = 0;
foreach (int item in leaderboard)
{
scores[ensuredThatIsLocal].text = item.ToString();
ensuredThatIsLocal++;
}
We see that it's a local variable. Local variables (or local scope in general) take precedence over class variables.
Though we can not answer this question since we have no idea what $$anonymous$$erboardTracker.lt.GetScores();
actually returns or what it does. This would be the relevant code. Whatever the method returns it has to ensure to limit the number of elements returned to the number of "Text$$anonymous$$eshProUGUI" elements in the scores array. So if there are 10 elements in the scores array, the GetScores method must not return more than 10 elements. Since we don't know what this method does we can't say anything here.
All we can say for sure is that if he gets an index out of bounds exception in line 15 he actually returned more elements than he has textmeshes in the scores array. This approach is generally dangerous. Relying on a certain number of elements from a seperate module / function is bad design. This would make more sense:
int count = $$anonymous$$athf.$$anonymous$$in(scores.Length, leaderboard.Count);
for (int i = 0; i < count; i++)
{
scores[i].text = leaderboard[i].ToString();
}
This ensures to never get an index out of bounds since it always uses the smaller item count. Though one might want to clear the remaining "scores" text meshes with an empty string in case there was other information before. You can just add this after the code i just posted:
for(int i = count; i < scores.Length; i++)
{
scores[i].text = "";
}
This will always work. In case count is equal to scores.Length this for loop will not run at all
got it, you're right, the name precedence in local before global, so thats not the problem... sorry
also, excuse me but, dont you mean to clear code need to be added before the code of new score text assignment?, if you clear just after the assignment you ever will show the score text, just ""
on the frame update, clear before grant you to not have garbage on the new text assignment.
please excuse me if I'm wrong again...