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

时间:2020-11-04 06:39:28

标签: c# forms variables

让我解释一下:

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

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

1 个答案:

答案 0 :(得分:0)

您可以保存布尔值。

这是您的操作方式:

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;
    }
}

只需确保在启动时加载它。 此保存方法还可以与其他任何东西一起使用,例如ints和您自己的类(<!>,前提是它在<!>的顶部带有“ [System.Serializable]”,并且您可以修改保存/加载的数据类型。 )

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