Reloading XML asset in Unity

2019-03-02 14:58发布

I am storing the progress of the game in XML file. Since the player can choose the round they want to play, but not repeat a round once completed. The files are being editted and updated correctly, however, the changes are not reflecting inside the game until i restart the game.

I had been using AssetDatabase.ImportAsset() until now, but i need an alternative for android export.

1条回答
Summer. ? 凉城
2楼-- · 2019-03-02 15:34

The good news is in Unity it's incredibly easy to save/read text files.

One absolutely key point...

An extremely confusing fact about Unity is that, quite simply, you must use Application.persistentDataPath (all platforms, all the time, every single time - no exceptions). "It's that simple!"

For some reason, starting a few years ago there came to be some code samples on the www about using other paths and accessing other folders. (A) there is uttelry no reason, whatsoever, to use any other folders or oaths (B) you simply can not use any other folders or paths.

It's incredibly easy to write and read files in Unity.

using System.IO;
// IO crib sheet..
// filePath = Application.persistentDataPath+"/"+fileName;
// check if file exists System.IO.File.Exists(f)
// write to file File.WriteAllText(f,t)
// delete the file if needed File.Delete(f)
// read from a file File.ReadAllText(f)

that's all there is to it.

string currentText = File.ReadAllText(filePath);

Note that you ask regarding your specific XML files, "should I add them manually on the first run"

It's simple, your algorithm is, to get the file information ...

public string GetThatXMLStuff()
 {
 filePath = Application.persistentDataPath+"/"+"defaults.txt";
 .. check if it already exists:
 if ( ! System.IO.File.Exists(f) )
   {
   .. put in the default/blank/whatever file
   string default = "blah"
   File.WriteAllText(f,default)
   }
 .. now you know it exists. just get it
 return File.ReadAllText(f);
 }

it's really that simple - nothing to it. (PS, I don't know about your specific situation, whether you should name the file ".txt" or ".xml" - really doesn't matter either way other than to make it clear or your colleagues; try both.)

查看更多
登录 后发表回答