【发布时间】: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