读取数据脚本(如果是第一次进入游戏,就初始化数据)
public static class PlayerDataReader
{
/// <summary>
/// 数据储存的路径(依据自己情况改变,前面的Application.datapath不能动,在Unity里面就是Assets目录)
/// </summary>
public static readonly string m_DataPath =
Application.dataPath + "/PlayerDatas.data";
/// <summary>
/// 从文件加载到的数据类
/// </summary>
public static PlayerDatas m_PlayerDatas = new PlayerDatas();
/// <summary>
/// 从数据文件读取数据,并赋值给m_PlayerDatas类
/// </summary>
public static void ReadPlayerData()
{
if (!File.Exists(m_DataPath))
{
File.Create(m_DataPath).Dispose();
m_PlayerDatas.PlayerDataInstance.Add(new OneOfPlayerDatas{Hello = 233});
PlayerDataSaver.SavePlayerData();
}
using (Stream file = File.OpenRead(m_DataPath))
{
m_PlayerDatas = PlayerDatas.Parser.ParseFrom(file);
}
}
}
保存数据文件
public static class PlayerDataSaver
{
public static void SavePlayerData()
{
using (Stream output = File.OpenWrite(PlayerDataReader.m_DataPath))
{
PlayerDataReader.m_PlayerDatas.WriteTo(output);
}
}
}
在Unity的Start函数中,首次运行游戏
//读取
PlayerDataReader.ReadPlayerData();
//打印
Debug.Log(PlayerDataReader.m_PlayerDatas.PlayerDataInstance[0].Hello);
//修改
PlayerDataReader.m_PlayerDatas.PlayerDataInstance[0].Hello= 188;
//保存
//PlayerDataSaver.SavePlayerData();
//打印
Debug.Log(PlayerDataReader.m_PlayerDatas.PlayerDataInstance[0].Hello);
第二次运行游戏,结果如我们所料,由于没有对数据进行保存,所以结果还是233,188
退出游戏,对Start中的函数做如下修改
//读取
PlayerDataReader.ReadPlayerData();
//打印
Debug.Log(PlayerDataReader.m_PlayerDatas.PlayerDataInstance[0].Hello);
//修改
PlayerDataReader.m_PlayerDatas.PlayerDataInstance[0].Hello = 188;
//保存
PlayerDataSaver.SavePlayerData();
//打印
Debug.Log(PlayerDataReader.m_PlayerDatas.PlayerDataInstance[0].Hello);
运行两次,OK,教程结束