【问题标题】:Problem when saving an array of scriptable objects into a json file UNITY/C#将可编写脚本的对象数组保存到 json 文件 UNITY/C# 时出现问题
【发布时间】:2019-12-19 09:09:27
【问题描述】:

我试图将脚本对象数组的数据存储到序列化的 json 文件中,当我只保存 1 个对象时没有问题,但是当我尝试循环并保存所有数组时,它只保存了最后一个在数组中。知道如何解决这个问题吗?

C#代码-

 public static GameSaveManager instance;

[SerializeField] private ShopItem[] shopitems;
[SerializeField] private BackgroundShopItem[] backgroundShopItems;

private void Awake()
{
    if (instance == null)
    {
        instance = this;
    }
    else if (instance != this)
    {
        Destroy(this);
    }

    DontDestroyOnLoad(this);
}

public bool IsSaveFile()
{
    return Directory.Exists(Application.persistentDataPath + "game_save");
}

public void SaveGame()
{
    if (!IsSaveFile())
    {
        Directory.CreateDirectory(Application.persistentDataPath + "/game_save");
    }

    if (!Directory.Exists(Application.persistentDataPath + "/game_sava/data"))
    {
        Directory.CreateDirectory(Application.persistentDataPath + "/game_save/data");
    }

    BinaryFormatter bf = new BinaryFormatter();

    for (int i = 0; i < shopitems.Length; i++)
    {
        ShopItem si = shopitems[i];

        FileStream file = File.Create(Application.persistentDataPath + "/game_save/data/skins_save.txt");
        var json = JsonUtility.ToJson(si);
        bf.Serialize(file, json);
        file.Close();
    }
}

【问题讨论】:

  • 您能否通过粘贴代码来说明您是如何向ShopItem[] 添加项目的?
  • @HurpaDerpa ShopItem[] 是可编写脚本的对象,我只是在检查器中拖动填充数组
  • 您似乎在循环中关闭文件...您想在循环外关闭它。

标签: c# file unity3d serialization save


【解决方案1】:

在您的循环for (int i = 0; i &lt; shopitems.Length; i++) 中,您将每个文件保存到相同 位置 - Application.persistentDataPath + "/game_save/data/skins_save.txt",因此您的文件将被覆盖。只需使用不同的保存文件:Application.persistentDataPath + "/game_save/data/skins_save_{i}.txt"

如果您想将其序列化为一个文件,请考虑为其实现您自己的 Serializable 类,并将您的 ShopItem[] 数组保留在那里。

[Serializable]
public class SaveItems
{
    public ShopItem[] shopitems;
}

所以在你的 SaveGame() 中你会得到这样的东西:

public void SaveGame()
{
    // previous code here

    BinaryFormatter bf = new BinaryFormatter();

    SaveItems si = new SaveItems();
    si.shopitems = shopitems;    

    FileStream file = File.Create(Application.persistentDataPath + "/game_save/data/skins_save.txt");
    var json = JsonUtility.ToJson(si);
    bf.Serialize(file, json);
    file.Close();

}

【讨论】:

  • 我刚刚尝试了您所说的,但“{i}”被检测为字符串并且仅应用于文件名。我做错了什么?
  • 我编辑了帖子,重新加载查看。是的 {i} 应用于文件名,但实际上我假设您只想获取一个文件而不是一堆文件。
  • 我对此很陌生,所以让我问一下,最好为每个 shopItem 保存一个文件,还是只保存一个包含您在编辑回复中提到的所有已保存数据的文件?
  • 我认为将所有数据保存在一个地方是一个合理的想法,因为您的数据似乎很简单,并且假装全部加载。如果您想保存一个臃肿的类或实现单独的 shopItem 的加载,那么您应该考虑单独保存每个 shopItem。但这只是我的意见,我经验不足,无法在没有任何线索的情况下认为我的意见正确。
  • 感谢您的回复!而且,如何将数据存储在前面提到的不同文件中?所以我知道这两种方法:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 2022-08-22
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
相关资源
最近更新 更多