Hi there so I have a list of items, which contain usernames of the players that play my game. I have used the code below to display each of the items in the list into UI text of separate instantiated prefabs.
However lets say I run my game and create a user called bob and then I delete bob. The next time I run my game and create new users such as Andy and Tom. The UI text for each prefab will display bob ( even though I deleted bob and he is not in my list), then Andy, then Tom.
When I run a Debug.Log the correct values are printed in the console (Andy then Tom), but UI text acts a lot different. Any help would be much appreciated.
Code:
foreach (var user in leaderboardList)
{
Debug.Log(user.username);
Instantiate(leaderboardPrefab, leaderboardPanel.transform);
leaderboardPrefab.transform.Find("UsernameBackground").GetComponent<Text>().text = user.username.ToString();
It is bad practice to use “Find”. You should set up a reference properly as it is much safer.
It looks like what you are doing is accessing a text component attached to the same gameobject as this script, then setting that one text component to every username in the list. So by the end of the loop, you have set it to the last name in your collection.
What you want to do is set 3 or more different text components to each username right? So you need to reference each of these text components, or if the text component belongs on this prefab with the script, rather than looping over you could just set it on start. Or are you trying to set them all using one text component? If that’s the case then you are currently overwriting the string each iteration and you need to join the string to the end instead.
It’s a bit hard to tell as I don’t know the rest of your code or what’s being called from where. Is this some sort of manager script that’s responsible for setting all of them at once? or is this a script on each indivudal prefab responsible for setting it’s own text?
Close Unity => click CTRL+R => type %temp% and delete all files, and skip if you got skip window
Now also click CTRL+R => type temp and do delete + skip if possible
Restart your Computer and try
Thank you @Link17x . It works !!!