游戏开发中一定会涉及到游戏数据存储的问题
下面展示我在学习游戏数据存储时自己边学边写的代码。
Save类
[System.Serializable]
public class Save
{
public double distance = 0.0f;
public int garde = 0;
public string Name = "";
public double speed = 0;
}
自己做的案例是一个移动记录数据的案例,要定义成单实例模式
要控制物体的移动
public class SphereController : MonoBehaviour
{
//单实例模式
//private static SphereController instance;
//public static SphereController GetInstance()
//{
// if (instance == null)
// {
// instance = new SphereController();
// }
// return instance;
//}
//private static SphereController instance;
//public static SphereController Instance
//{
// get
// {
// if (instance == null)
// {
// instance = new SphereController();
// }
// return instance;
// }
//}
public static SphereController Instance;
//分数
public int Grade;
public double Speed;
public string Name;
public double Distance;
public Text text;
private void Awake()
{
Instance = this;
}
// Start is called before the first frame update
void Start()
{
Grade = 0;
Speed = 2f;
Name = "球";
Distance = 0f;
}
// Update is called once per frame
void Update()
{
//按下W键
if(Input.GetKeyDown(KeyCode.W))
{
transform.position += new Vector3(0, 0, 1);
Grade += 1;
Distance += 1f;
}
if(Input.GetKeyDown(KeyCode.S))
{
transform.position += new Vector3(0, 0, -1);
Grade += 1;
Distance += 1f;
}
if(Input.GetKeyDown(KeyCode.A))
{
transform.position += new Vector3(-1, 0, 0);
Grade += 1;
Distance += 1f;
}
if(Input.GetKeyDown(KeyCode.D))
{
transform.position += new Vector3(1, 0, 0);
Grade += 1;
Distance += 1f;
}
text.text = "Name: "+Name+"\nSpeed: "+Speed+"\nGrade: "+Grade+"\nDistance: "+Distance;
}
internal void ShowMessage(string v)
{
Debug.Log(v);
}
}
接下来就是存档和读档的方法
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using LitJson;
using System.Xml;
using UnityEngine;
using UnityEditor;
public class SaveAndRead : MonoBehaviour
{
//创建Save对象并存储当前游戏状态信息
private Save CreateSaveGO()
{
//新建Save对象
Save save = new Save();
save.Name = SphereController.Instance.Name;
save.speed = SphereController.Instance.Speed;
save.garde = SphereController.Instance.Grade;
save.distance = SphereController.Instance.Distance;
return save;
}
//通过读档信息重置我们的游戏状态
private void SetGame(Save save)
{
SphereController.Instance.Name = save.Name;
SphereController.Instance.Speed = save.speed;
SphereController.Instance.Grade = save.garde;
SphereController.Instance.Distance = save.distance;
}
//********************************二进制方法************************************************
//存档
public void SaveByBin()
{
// 序列化过程(将save对象转换为字节流)
//创建save对象并保存当前游戏状态
Save save = CreateSaveGO();
//创建一个二进制格式化程序
BinaryFormatter binaryFormatter = new BinaryFormatter();
//创建一个文件流
FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile" + "/byBin.txt");
//用二进制格式化程序的序列化方法来序列化Save对象,参数:创建的文件流和需要序列化的对象
binaryFormatter.Serialize(fileStream, save);
//关闭流
fileStream.Close();
//如果文件存在,则显示保存成功
if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
{
SphereController.Instance.ShowMessage("保存成功");
}
}
//读档
public void LoadByBin()
{
if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
{
//反序列化过程
//创建一个二进制格式化程序
BinaryFormatter binaryFormatter = new BinaryFormatter();
//打开一个文件流
FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open);
//调用格式化程序的反序列化方法,将文件流转换为一个Save对象
Save save = binaryFormatter.Deserialize(fileStream) as Save;
SetGame(save);
//关闭文件流
fileStream.Close();
SphereController.Instance.ShowMessage("读档成功");
}
else
{
SphereController.Instance.ShowMessage("存档文件不存在");
}
}
//*****************************************XML**************************************
//存档
public void SaveByXml()
{
Save save = CreateSaveGO();
//创建Xml文件的存储路径
string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";
//创建XML文档
XmlDocument xmlDoc = new XmlDocument();
//创建根节点,即最上层节点
XmlElement root = xmlDoc.CreateElement("save");
//设置根节点中的值
root.SetAttribute("name", "saveFile1");
//创建XmlElement
XmlElement Name = xmlDoc.CreateElement("Name");
Name.InnerText = save.Name.ToString();
root.AppendChild(Name);
XmlElement Speed = xmlDoc.CreateElement("Speed");
Speed.InnerText = save.speed.ToString();
root.AppendChild(Speed);
XmlElement Grade = xmlDoc.CreateElement("Grade");
Grade.InnerText = save.garde.ToString();
root.AppendChild(Grade);
XmlElement Distance = xmlDoc.CreateElement("Distance");
Distance.InnerText = save.distance.ToString();
root.AppendChild(Distance);
xmlDoc.AppendChild(root);
xmlDoc.Save(filePath);
if(File.Exists(Application.dataPath+"/StreamingFile"+"/buXML.txt"))
{
SphereController.Instance.ShowMessage("保存成功");
}
}
//读档
public void LoadByXml()
{
string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";
if(File.Exists(filePath))
{
Save save = new Save();
//加载XML文档
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
//得到存储的数据
XmlNodeList Name = xmlDoc.GetElementsByTagName("Name");
string name = Name[0].InnerText;
SphereController.Instance.Name = name;
XmlNodeList Speed = xmlDoc.GetElementsByTagName("Speed");
float speed =float.Parse(Speed[0].InnerText);
SphereController.Instance.Speed = speed;
XmlNodeList Grade = xmlDoc.GetElementsByTagName("Grade");
int grade = int.Parse(Grade[0].InnerText);
SphereController.Instance.Grade = grade;
XmlNodeList Distance = xmlDoc.GetElementsByTagName("Distance");
float distance = float.Parse(Distance[0].InnerText);
SphereController.Instance.Distance = distance;
SphereController.Instance.ShowMessage("读档成功");
}
else
{
SphereController.Instance.ShowMessage("存档文件不存在");
}
}
//***********************************************JSON***********************************************
//存档
public void SaveByJson()
{
Save save = CreateSaveGO();
string filePath = Application.dataPath + "/StreamingFile" + "/byJson.txt";
//利用JsonMapper将Save对象转换为Json格式的字符串
string saveJsonStr = JsonMapper.ToJson(save);
//将这个字符串写入到文件中
//创建一个StreamWriter,并将字符串写入
StreamWriter sw = new StreamWriter(filePath);
sw.Write(saveJsonStr);
//关闭写入流
sw.Close();
AssetDatabase.Refresh();
}
//读档
public void LoadByJson()
{
string filePath = Application.dataPath + "/StreamingFile" + "/byJson.txt";
//创建一个StreamReader,用来读取流
StreamReader sr = new StreamReader(filePath);
//将读取到的流赋值给saveJsonStr
string saveJsonStr = sr.ReadToEnd();
sr.Close();
//将字符串转换为Save对象
Save save = JsonMapper.ToObject<Save>(saveJsonStr);
SetGame(save);
}
}