分享

【新提醒】【分享序列化脚本~~备忘随时拿来用~】

 Dragon_chen 2015-11-18
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();
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多