- Home /
Accessing arbitrary files within a web build
Is it possible to access files within the unity3d package from scripts using standard file IO? Specifically what I'm looking to do is open an xml settings file and deserialize an object from it. I do realize it's possible to dump the xml on the server with the unity3d file, but I would much prefer to have it stored within the package.
Essentially I'm looking to do the following, with the file access being the missing piece:
Stream stream = null;
MyObject myObj = null;
try
{
stream = DoSomeUnityMagic();
myObj = serializer.Deserialize(stream);
}
catch (Exception)
{
Debug.Log("Failed to load object");
}
finally
{
if (null != stream)
{
stream.Close();
}
}
For anyone that comes hunting, the full solution is something like this:
MyObject myObj = null;
string resourcePath = "path/to/resource"; // Excluding extension, as usual
try
{
TextAsset myAsset = (TextAsset)Resources.Load(resourcePath, typeof(TextAsset));
Byte[] bytes = Encoding.UTF8.GetBytes(myAsset .text);
using (MemoryStream stream = new MemoryStream(bytes))
{
myObj = (MyObject)(new XmlSerializer(typeof(MyObject))).Deserialize(stream);
}
}
catch (Exception ex)
{
Debug.Log("Failed to deserialize data from resource " + resourcePath + " (" + ex.Message + ")");
Debug.Log(ex.StackTrace);
}
Also worth noting is that the web player doesn't support the default encoding which .Net serialization spits out, so when serializing an object it's important to set the encoding:
SerializeTestClass test = new SerializeTestClass();
test.Text = "Booyah from xml";
string path = "xmlfile.xml";
try
{
using (XmlTextWriter writer = new XmlTextWriter(File.Create(path), Encoding.UTF8))
{
XmlSerializer serializer = new XmlSerializer(typeof(SerializeTestClass));
serializer.Serialize(writer, test);
}
}
catch (Exception) { }
If you need the data to change over time (you called it a "settings file") then you should look at PlayerPrefs. http://unity3d.com/support/documentation/ScriptReference/PlayerPrefs.html
Actually Eric's answer was exactly what I needed, these aren't user settings, but trained AI settings that change often enough to be a pain to update in the inspector, but won't change within the build itself. Thanks for the suggestion though.