序列化存档之备忘脚本
序列化存档涉及的参数比较多,猛地一下始终是记不住。花时间把比较完整的代码记下来,并做好注释,这样就比较方便以后的使用。
using UnityEngine; using System.Collections; using System; using System.IO; using System.Collections.Generic; using System.Xml; using System.Runtime.Serialization.Formatters.Binary; /// <summary> /// 存档 /// </summary> public class SaveData : MonoBehaviour { string data=Application.dataPath + "/SaveData.dat"; [Serializable] public class SaveDataClass{ public string ID;//关卡号 public string name;//关卡名称 public string maxScore{ get; set;}//每关的最高分 public string starLev{ get; set;}//有星级就是通关,没有就是未通关 } public List<SaveDataClass> dataList=new List<SaveDataClass>(); void Awake() { DontDestroyOnLoad (this.gameObject); if (File.Exists (data)) {//再次玩时读取存档 Read (); } else { ReadXML ();//读取XML关卡数据 } } void ReadXML(){ dataList.Clear(); TextAsset t = (TextAsset)Resources.Load("SaveData");//XML文件,里面放置所有关卡的数据 StringReader sr=new StringReader(t.text); XmlDocument doc = new XmlDocument(); doc.Load(sr); XmlElement root = doc.DocumentElement; XmlNodeList nodes = root.SelectNodes("SaveData"); for (int i = 0; i < nodes.Count; i++) { XmlNode node = (XmlElement)(nodes.Item(i)); SaveDataClass d=new SaveDataClass(); d.ID = node.Attributes.Item(0).InnerText; d.name = node.Attributes.Item(1).InnerText; d.maxScore = node.Attributes.Item(2).InnerText; d.starLev= node.Attributes.Item(3).InnerText; dataList.Add(d); } Save(); } void Read(){ FileStream fs = new FileStream(data, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); dataList = (List<SaveDataClass>)(bf.Deserialize(fs)); fs.Close(); } //退出游戏或通关时调用 public void Save(){ FileStream fs = new FileStream(data, FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs,dataList); fs.Flush(); fs.Close(); } }
存档配置文件要提前用Excel写好并转换,格式如下:
<?xml version="1.0" encoding="UTF-8"?> <Root> <SaveData ID="0" sceneName="Lev01" maxScore="0" starLev="0" /> <SaveData ID="1" sceneName="Lev01" maxScore="0" starLev="0" /> </Root>