[英]XML file not getting written using Unity and C#
我試圖將列表保存為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;
}
如果調用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");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.