首页 > 解决方案 > 我的 C# 游戏有问题(JSON / 更新 / 创建)

问题描述

我目前正在开发我的 C# 游戏。我向当地 Discord 的许多人寻求帮助,但我从来没有得到好的或有用的答案。我目前正在开发我的游戏播放器。问题是我需要一种使用 JSON 序列化保存和加载的好方法。

我在这个问题末尾的代码不起作用,我的想法很低。我确实重写了这个问题的代码。这是一个例子。

我只需要为我的 Player 更新一些值。

private void button_Click(object sender, EventArgs e)
{
    random_number1 = rnd.Next(0, 10);
    random_number2 = rnd.Next(0, 5);

    string path = Application.LocalUserAppDataPath + "/saves/" + player + ".save";

    PlayerProfile player = JsonConvert.DeserializeObject<PlayerProfile>(File.ReadAllText(pfad));

    player.PlayerAttribute1 += random_number1;
    player.PlayerAttribute2 += random_number2;

    MessageBox.Show(string.Format("You get {0} Random_1 and {1} Random_2", random_number1, random_number2), "Alert");

    JsonConvert.SerializeObject(player);

    UpdateUI();
}

如果您需要任何其他信息,例如我的 PlayerProfile 类或我的脚本的其他片段,请将其写在答案或 pn 中。

标签: c#jsonwindows

解决方案


您可能应该再次写入您的文件:

    private void button_Click(object sender, EventArgs e)
    {
        random_number1 = rnd.Next(0, 10);
        random_number2 = rnd.Next(0, 5);

        string path = Application.LocalUserAppDataPath + "/saves/" + player + ".save";

        PlayerProfile player = JsonConvert.DeserializeObject<PlayerProfile>(File.ReadAllText(pfad));

        player.PlayerAttribute1 += random_number1;
        player.PlayerAttribute2 += random_number2;

        MessageBox.Show(string.Format("You get {0} Random_1 and {1} Random_2", random_number1, random_number2), "Alert");

        
        // Write again in your file system
        File.WriteAllText(path, JsonConvert.SerializeObject(player));
        UpdateUI();

    }

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-5.0


推荐阅读