I have a prefab thats nothing more than two text fields.
One is called UserName, and the second called Score.
I instantiate the prefab via:
foreach (string data in userNameList)
{
GameObject scoreEntryTemp = (GameObject)Instantiate(playerScorePrefab);
scoreEntryTemp.transform.SetParent(this.transform, false);
scoreEntryTemp.transform.Find("UserName").GetComponent<Text>().text = data;
}
And already change the username with the last line. But now I’ve come to a problem. I have a second list called userScoreList that contains a list of integers that have to go into the text field “Score”.
How would I best change the “Score” text from here?
First i would create a component for the prefab:
public class PlayerScoreDisplay: MonoBehaviour
{
public Text userName;
public Text score;
}
Then change the two List into a single Dictionary, this way when you look for a player you can get it’s correspondent score, or even later on instead of storing only a float you can create an object PlayerData and get whatever you want related to that player, just change the dictionary to “YourClass” instead of the current float.
Dictionary<string, float> _playersData = new Dictionary<string, float> ();
Your for loop will be like:
foreach (KeyValuePair<string, float> __playerData in _playersData)
{
PlayerScoreDisplay scoreEntryTemp = Instantiate(playerScorePrefab);
scoreEntryTemp.transform.SetParent(this.transform, false);
scoreEntryTemp.userName.text = __playerData.Key;
scoreEntryTemp.score.text = __playerData.Value;
}
If you intend to use a PlayerData object in the dictionary make the foreach loop trough the Keys (string : userName )instead of pair.
foreach (string __userName in _playersData.Keys)
Thanks for the comments, the answer to it was actually pretty simple as a friend pointed out.
int i = 0;
int maxHighscoreCounter = 0;
int maxHighscoreLines = 14;
void Start () {
LoadFromFile();
string[] names = userNameList.ToArray();
int[] scores = userScoreList.ToArray();
Array.Sort(scores, names);
Array.Reverse(scores);
Array.Reverse(names);
foreach (int data in scores)
{
if (maxHighscoreCounter <= maxHighscoreLines)
{
GameObject scoreEntryTemp = (GameObject)Instantiate(playerScorePrefab);
scoreEntryTemp.transform.SetParent(this.transform, false);
scoreEntryTemp.transform.Find("UserName").GetComponent<Text>().text = names*;*
scoreEntryTemp.transform.Find(“Score”).GetComponent().text = data.ToString();
i++;
maxHighscoreCounter += 1;
}
}
}
It puts both lists into arrays, sorts them and outputs them inversed so that I can use it properly for a scoretable.