【发布时间】:2020-04-27 21:17:01
【问题描述】:
[编辑] 我明白为什么帖子被降级了。我不知道为什么,但我确定我做错了什么。所以,如果你有时间,请考虑评论并告诉我这篇文章有什么问题,然后再降级:) 谢谢
所以,我有我的保存系统的这一部分,我想在其中序列化由一个名为 CaptureState 的函数给出的嵌套字典。在我的调试中,我检查 CaptureState 是否返回具有 SceneManager.GetActiveScene().buildIndex 键下的值的字典。它证明,该方法实际上返回了所需的字典。但是,如果我序列化它然后反序列化它,字典就会搞砸了。它只包含 1 个项目(它应该包含 7 个),并且该项目位于键 1 下(SceneManager.GetActiveScene().buildIndex 在测试时为 0)(这些东西在附加代码中没有显示,但是相信我 :D) 当然(正如我们在附加的代码 sn-p 中看到的那样),尝试访问键 SceneManager.GetActiveScene().buildIndex(即 0) 会引发 KeyNotFoundException。 如果重要,我会使用 Unity。
void SaveFile(string saveFile)
{
string path = GetPathFromSaveFile(saveFile);
using(FileStream stream = File.Open(path, FileMode.Open))
{
stream.Position = 0;
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, CaptureState(LoadFile(path, stream, formatted)));
//From this point, testing purposes
stream.Position = 0;
Dictionary<int, Dictionary<string, object>> testDicta = (Dictionary<int, Dictionary<string, object>>)CaptureState(LoadFile(path, stream, formatter));
print(testDicta[SceneManager.GetActiveScene().buildIndex].Count); // Shows the proper count
stream.Position = 0;
Dictionary<int, Dictionary<string, object>> testDict = (Dictionary<int, Dictionary<string, object>>)formatter.Deserialize(stream);
print(testDict[SceneManager.GetActiveScene().buildIndex].Count); // Throws me a KeyNotFoundException
}
}
【问题讨论】:
标签: c# dictionary unity3d serialization binaryformatter