简述:这里我们使用c#中的序列化来实现数据的存储和读取。
功能简述:保存时,我们将我们要保存的数据序列化后,新建一个文件保存起来。
读取时,我将我们要读取的数据反序列化,然后读取出来,代码如下:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>
/// 这个类实现了Save 和Load 两个方法来实现保存和加载功能。
/// 这个方法需要配合游戏中需要保存的数据一起使用,这个类最好只提供方法。
/// 游戏的数据类这里只是简要的随便写了一个,以后要放在其他地方。
/// </summary>
public class SaveManager : MonoBehaviour {
//建立一个数据容器,用来保存数据源
public static List<GameData> dataList = new List<GameData>();
private static SaveManager _instance;
public static SaveManager Instance
{
get
{
return _instance;
}
}
void Awake()
{
_instance = this;
}
/// <summary>
/// 保存游戏数据。首先用用一个序列化的类GameData来存储数据
/// 然后将该类加入到本类的数据列表dataList中,再利用BinaryFormatter来将对象数据保存在一个文件中
/// 当调用本方法后,将目标数据保存在本地文件中
/// </summary>
public void SaveGame()
{
dataList.Clear();
dataList.Add(GameData.currentGame);
FileStream file = File.Create(Application.dataPath + "/Save/Savefile.sf");
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(file, dataList);
file.Close();
}
/// <summary>
/// 此方法用于读取本地文件后,用反序列的方式把数据还原出来,并保存在dataList中
/// 当调用这个方法后,本类中的数据容器dataList就是上次玩家保存的数据
/// </summary>
public void LoadGame()
{
if(File.Exists(Application.dataPath + "/Save/Savefile.sf"))
{
FileStream file = new FileStream(Application.dataPath + "/Save/Savefile.sf",FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
dataList = bf.Deserialize(file) as List<GameData>;
file.close();
}
}
}
/// <summary>
/// 这里是表示序列化的数据,这个GameData类里的数据都可以被序列化。
/// 注意:这里序列化的数据只能包括原生c#中的数据类型,unity里的数据类型,比如vector3是不可被序列化的。此外,GameData这个类也不能
/// 继承Monobehaviour,若继承Monob类,也不可序列化。
/// </summary>
[System.Serializable]
public class GameData
{
public static GameData currentGame = new GameData();
public int level;
public int hp;
public string name;
public int stage;
public float positionX;
public float positionY;
public float positionZ;
}
这样,一个非常简单的保存和读取原型就出来了。