- Home /
TextAsset vs StreamReader
public class XMLParser {
private string docName = @"/ArtifactExampleXML.xml";
private string inputLocation = Application.dataPath;
public XMLParser(){
inputLocation += (@"/Resources"+docName);
}
public List<Artifact> Deserialize(){
XmlSerializer xmls = new XmlSerializer(typeof (List<Artifact>));
TextReader tr = new StreamReader(inputLocation);
List<Artifact> artifactList = (List<Artifact>)xmls.Deserialize(tr);
tr.Close();
return artifactList;
}
}
This is the only way I could figure out how to Deserialize my xml file from within a folder in Unity. So this works fine when I hit play to do a test run, but when I build it for a WebPlayer and run through it I can see that it's not reading the xml file.
I've seen people suggest to load it as a TextAsset, but from there I can't figure how to get my data out of it. How can I load it as a Streamreader so I can just Deserialize it?
Answer by Eric5h5 · Jul 13, 2011 at 06:29 PM
There is no local file IO when making a webplayer. You can load the file from a server, but not locally. The text in a TextAsset is just that:
public TextAsset myText;
void Start () {
string contents = myText.text;
}
So I can either put the xml file up where the game is hosted or write a custom parser that goes through the xml-converted-to-one-giant-string? If I choose the former (which is probably the better solution) how do load it so it's still a StreamReader?
@claudekennilol: I don't think you can; when you get the file, you'd use the WWW class, and the file will be in WWW.text after it's downloaded.
private string inputLocation = Application.dataPath;
inputLocation += (@"/Resources"+docName);
I did another test with just an exe build, and it still wasn't reading the xml data, I'm thinking I need to change my inputLocation to something else, but it took me a long time just to figure that that worked.. Is there even a way in Unity to open a StreamReader from a file located somewhere in my build?
@claudekennilol: There is no literal Resources folder in a build; all assets are compiled into assets files per level. (Also, if there was, you'd use "/Resources/"+docName.)
Answer by claudekennilol · Jul 20, 2011 at 07:52 PM
After more testing, turns out Application.dataPath is protected and can't be accessed outside of Unity (or something like that, it's a security breach to allow access to it, at least how I was calling it upon class initiation).
So that was the problem. When I put the xml in a resources folder and and loaded it as a TextAsset then deserialized it I was able to deserialize it just fine.