![](/img/trans.png)
[英]Checking if a file exists and if it doesn't creating it from embedded resource
[英]Problem getting value from deserialized file if doesn't exists
我目前正在尝试设置一个“firstRun”布尔值,以仅在第一次启动应用程序时运行一段代码。
游戏数据文件
[System.Serializable]
public class GameData
{
public static string saveFileName = "Pixel.pixel";
public double money;
public bool firstRun;
public GameData()
{
money = GameController.Instance.CurrentCash;
}
}
保存系统文件
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem
{
public static void SaveData()
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/" + GameData.saveFileName;
FileStream stream = new FileStream(path, FileMode.Create);
GameData data = new GameData();
formatter.Serialize(stream, data);
stream.Close();
}
public static GameData LoadData()
{
string path = Application.persistentDataPath + "/" + GameData.saveFileName;
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
GameData data = formatter.Deserialize(stream) as GameData;
stream.Close();
return data;
}
else
{
return null;
}
}
}
GameController.cs 部分
public void Start()
{
Setup(START_CASH);
/*AddCash(START_CASH);*/
}
private void Setup(double value)
{
GameData data = SaveSystem.LoadData();
if (!data.firstRun)
{
CurrentCash += value;
SaveSystem.SaveData();
}
else
{
CurrentCash = data.money;
SaveSystem.SaveData();
}
UI.CashDisplay.text = ShortScaleString.parseDouble(CurrentCash, 1, 1000, scientificFormat);
}
我的问题是我需要检查“data.firstRun”是否为假/不存在来运行设置部分,但我真的不知道如何实现
您应该只返回一个新的“GameData”,带有您喜欢的值(true 或 false):
public static GameData LoadData()
{
string path = Application.persistentDataPath + "/" + GameData.saveFileName;
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
GameData data = formatter.Deserialize(stream) as GameData;
stream.Close();
return data;
}
else
{
return new GameData { firstRun = true };
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.