打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
【新提醒】【分享序列化脚本~~备忘随时拿来用~】
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();
    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C# 二进制BinaryFormatter进行序列化与反序列化
快速掌握VB.NET读写文本文件操作
关于BinaryFormatter
C#序列化和反序列化 (BinaryFormatter、SoapFormatter、XML序列化)
C# DataSet对象序列化并压缩和反序列化及解压缩
为什么需要序列化,以及序列化的一些操作【收录】
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服