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();
}
}
联系客服