我正在尝试将列表保存到XML中,稍后将 XML重新加载到该列表中。
除了实际的Save
方法之外,其中大多数似乎都能正常工作。
这是我的代码。问题是没有创建 SaveInformation.xml 。
[XmlRoot("SaveInformation")]
public class SaveInformation {
[XmlArray("stat")]
[XmlArrayItem("PlayerData")]
public PlayerData[] stat;
public void Save(string path){
var serializer = new XmlSerializer(typeof(SaveInformation));
using(var stream = new FileStream(path,FileMode.Create)){
serializer.Serialize (stream, this);
vstream.Close();
}
}
public static SaveInformation Load(string path){
var serializer = new XmlSerializer(typeof(SaveInformation));
using(var stream = new FileStream(path,FileMode.Open)){
return serializer.Deserialize (stream) as SaveInformation;
stream.Close();
}
}
}
以下是Load
和Save
方法:
using UnityEngine;
using System.Collections;
using System.IO;
public class StoreData : MonoBehaviour {
public static void Load(){
var saveInformation = SaveInformation.Load(
Path.Combine(Application.dataPath, "SaveInformation.xml"));
Debug.Log("Loaded");
}
public static void Save(){
SaveInformation obj = new SaveInformation();
obj.Save(Path.Combine(Application.persistentDataPath,
"SaveInformation.xml"));
Debug.Log("Saved");
}
}
以下是应该传递XML的类 stat 和 PlayerData
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
[XmlRoot("PlayerDatabaseCollection")]
public class PlayerDatabase : MonoBehaviour {
[XmlArray("stat")]
[XmlArrayItem("PlayerData")]
public List<PlayerData> stat = new List<PlayerData>();
}
这是数据本身
using UnityEngine;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
[System.Serializable]
public class PlayerData {
[XmlAttribute("name")]
public string Name;
[XmlAttribute("current")]
public int Current;
[XmlAttribute("max")]
public int Max;
}
答案 0 :(得分:0)
如果您调用save,则不应创建类的新实例。确保您只有一个获得加载和保存的实例...
public class StoreData : MonoBehaviour {
// this will hold your data (but in the snippets you provided I
// can't see how you are accessing this, maybe this should be public)
private static SaveInformation saveInformation = null; // keep one instance
private static string savepath = Application.dataPath; // or Application.persistentDataPath ?
private static string savePathFile = Path.Combine(savepath, "SaveInformation.xml");
public SaveInformation Instance {
get {
return (saveInformation ?? new SaveInformation());
}
}
public static void Load(){
saveInformation = SaveInformation.Load(savePathFile);
Debug.Log("Loaded");
}
public static void Save(){
if (saveInformation != null) {
saveInformation.Save(savePathFile);
Debug.Log("Saved");
} else {
Debug.Log("No saveinformation yet");
}
}
}