是否有变量不会在每次启动应用程序时重置?



让我解释一下:

假设我有一个Boolean变量,在编写程序代码时,我将其设置为False。现在,每次构建/运行应用程序时,这个Boolean变量都会增加到False

我希望在用户输入特定字符串的情况下,Boolean将更改为True,然后每次我重新运行应用程序时,它将保持为True的值。换句话说,变量现在将重置为True

您可以保存布尔值。

以下是您的操作方法:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class SaveSystem
{
// =====Saving=====
// "path" should be filled with the full path of the save directory, including the file name and the file extension.
public static void Save(bool boolean, string path)
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Create);
formatter.Serialize(stream, boolean);
Debug.Log($"Bool saved at {path}");
stream.Close();
}

// =====Loading=====
// "path" should be filled with the full path of the save directory, including the file name and the file extension.
public static bool LoadOptions(string path)
{
if(!File.Exists(path))
{
Console.WriteLine($"Options file not found in {path}"); //For debugging, is removable
return false;
}
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
bool stuff = formatter.Deserialize(stream) as bool;
Debug.Log($"Bool loaded at {path}");
stream.Close();
return stuff;
}
}

只要确保在启动时加载即可。这种保存方法也适用于任何其他东西,如int和您自己的类(<!>前提是它顶部有<[System.Serializable]",并且您可以修改它保存/加载的数据类型。(

[编辑]这是众多保存算法之一。这是一种保存到二进制文件的方法。如果您想保存到文本文件,其他答案可能会有所帮助。请记住,二进制文件比text/xml文件更难篡改,因此这是推荐的保存方法。

最新更新