Reloading XML asset in Unity

我与影子孤独终老i 提交于 2019-11-28 10:36:23

问题


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:


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

The key point...

You must use Application.persistentDataPath (all platforms, all the time - no exceptions). "It's that simple!"

(A) There is utterly no reason, whatsoever, to use any other folders or paths.

(B) Indeed, you simply can not use any other folders or paths.

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

using System.IO;
// IO crib sheet..
//
// get the file path:
// f = 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);

Regarding the question here, "should I add them manually on the first run"

It's simple ...

public string GetThatXMLStuff()
 {
 f = Application.persistentDataPath+"/"+"defaults.txt";

 // check if it already exists:

 if ( ! System.IO.File.Exists(f) )
   {
   // First run. Put in the default file
   string default = "First line of file.\n\n";
   File.WriteAllText(f, default);
   }

 // You know it exists no matter what. Just get the text:
 return File.ReadAllText(f);
 }

It's really that simple - nothing to it.



来源:https://stackoverflow.com/questions/36222700/reloading-xml-asset-in-unity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!