How to load XML files in Unity Web Player?
In my Towercraft game, I need to load level/achievement information from the XML files in the Resources folder. Also the game is built in Web Player, so the XmlDocument.Load() won't work in this case. The solution is to use WWW class to load file, and then use XmlDocument to load it as string.
- string path = Application.dataPath + @"/Resources/Level.xml";
- WWW www = new WWW(path);
- yield return www;
- XmlDocument xmlDoc = new XmlDocument();
- xmlDoc.LoadXml(www.text);
Here's the complete code that loads level/achievement information from the XML files in the resources folder:
- using UnityEngine;
- using System.Collections;
- using System.Xml;
- public class XmlDataReader : MonoBehaviour {
- private XmlDocument xmlLevelDoc;
- private XmlDocument xmlAchievementDoc;
- private string levelPath;
- private string achievementPath;
- private bool isLoaded;
- void Start()
- {
- isLoaded = false;
- levelPath = Application.dataPath + @"/Resources/Level.xml";
- achievementPath = Application.dataPath + @"/Resources/Achievement.xml";
- StartCoroutine(LoadXML());
- }
- IEnumerator LoadXML()
- {
- if(Application.isWebPlayer){
- WWW wwwLevel = new WWW(levelPath);
- yield return wwwLevel;
- WWW wwwAchieve = new WWW(achievementPath);
- yield return wwwAchieve;
- xmlLevelDoc = new XmlDocument();
- xmlLevelDoc.LoadXml(wwwLevel.text);
- xmlAchievementDoc = new XmlDocument();
- xmlAchievementDoc.LoadXml(wwwAchieve.text);
- }
- else{
- xmlLevelDoc = new XmlDocument();
- xmlLevelDoc.Load(levelPath);
- xmlAchievementDoc = new XmlDocument();
- xmlAchievementDoc.Load(achievementPath);
- }
- isLoaded = true;
- }
- }