C# BinaryWriter/BinaryReader - 读取器顺序与写入顺序不匹配



我有一些体素数据,我想使用BinaryWriter保存,然后使用BinaryReader读取,但我遇到了一些问题。

当我再次阅读它时,数据似乎处于不同的顺序,因此,我生成的体素块得到错误的值。据我了解,您必须按照编写数据的顺序读取数据,我应该这样做。
我看了几个例子,但它们都把我引向了这个问题。我不知道我做错了什么。

我在这里创建了一些测试代码,首先写入文件,然后立即读取它,然后检查加载的值是否与它保存的值匹配。结果总是它不匹配,它总是停在同一个地方。

Block[] blocksToSave = chunk.blocks.GetBlocks();
using (BinaryWriter writer = new BinaryWriter(File.Open(Application.persistentDataPath + "/test.bin", FileMode.OpenOrCreate)))
{
for (int i = 0; i < blocksToSave.Length; i++)
{
writer.Write(blocksToSave[i].id); // The ID is just a byte value.
}
}
byte[] loadedBlocks = new byte[Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE]; // 16 * 16 * 16
using (BinaryReader reader = new BinaryReader(File.Open(Application.persistentDataPath + "/test.bin", FileMode.Open)))
{
int pos = 0;
int index = 0;
int streamLength = (int)reader.BaseStream.Length;
while (pos < streamLength)
{
byte id = reader.ReadByte();
loadedBlocks[index] = id;
pos += sizeof(int);
index++;
}
}
if (blocksToSave.Length != loadedBlocks.Length)
{
Debug.LogError("Sizes does not match!");
return;
}
for (int i = 0; i < blocksToSave.Length; i++)
{
if (blocksToSave[i].id != loadedBlocks[i])
{
Debug.LogError("Expected " + blocksToSave[i].id + " but got " + loadedBlocks[i] + " at index " + i + ".");
return;
}
}

任何帮助了解问题都非常感谢!
谢谢

pos += sizeof(int);

应该是

pos += sizeof(byte);

最新更新