Leader-board not working consistently
I am working on a leaderboard script for my game. It reads XML and then populates that into a list then uses a UI prefab to populate a scroll view. It works... just not consistently. Sometimes it will load sometimes it will not and it never loads outside of the Unity editor like on mobile devices. I could use another set of eyes to help me with this issue.
Leaderboard.cs
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.Xml;
using System.IO;
using System.Collections.Generic;
[System.Serializable]
public class HighScore
{
public string Rank;
public string Name;
public string Score;
}
public class Leaderboard : MonoBehaviour
{
public GameObject scorePrefab;
public List<HighScore> scoreList;
public Transform contentPanel;
public Text errorMessage;
void Awake()
{
StartCoroutine(GetText());
}
private void parseXmlFile(string xmlData)
{
int rank = 0;
errorMessage.enabled = true;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new StringReader(xmlData));
string xmlPathPattern = "XML PATH INFO";
XmlNodeList myNodeList = xmlDoc.SelectNodes(xmlPathPattern);
foreach(XmlNode node in myNodeList)
{
rank++;
XmlNode name = node.FirstChild;
XmlNode scor = name.NextSibling;
//int newScore = XmlConvert.ToInt32(scor.ToString());
HighScore score = new HighScore();
score.Rank = rank.ToString() + " - ";
score.Name = name.InnerXml;
score.Score = scor.InnerXml;
scoreList.Add(score);
}
errorMessage.enabled = false;
PopulateScores();
}
IEnumerator GetText()
{
UnityWebRequest www = UnityWebRequest.Get("URL TO MY XML HERE");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
errorMessage.enabled = true;
errorMessage.text = www.error.ToString();
}
else
{
// Show results as text
parseXmlFile(www.downloadHandler.text);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
}
}
private void PopulateScores()
{
foreach (var highscore in scoreList)
{
GameObject scorePanel = Instantiate(scorePrefab) as GameObject;
HighScorePrefab prefab = scorePanel.GetComponent<HighScorePrefab>();
prefab.Rank.text = highscore.Rank;
prefab.Name.text = highscore.Name;
prefab.Score.text = highscore.Score;
scorePanel.transform.SetParent(contentPanel);
}
}
}
HighScorePrefab.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HighScorePrefab : MonoBehaviour
{
public Image Image;
public Text Rank;
public Text Name;
public Text Score;
}
Comment
Answer by RoninGT · Nov 14, 2018 at 04:23 PM
UPDATE: I got it to load randomly on my android device didn't change any code. It's like it loads when it wants to. I am thinking its calling to populate the list before the code has had time to parse the xml fully. Any feedback?