Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
993 views
in Technique[技术] by (71.8m points)

unity3d - Reloading XML asset in Unity

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

";
   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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...