BinaryFormatter 似乎是附加而不是覆盖
BinaryFormatter seems to be appending rather than overwriting
我创建了一个加载文件来按顺序跟踪游戏中创建的所有角色。有 15 个字符的限制,因此每当玩家创建新角色时,我都需要检查是否达到了该限制。但是,当我尝试修改加载文件中的对象容器并再次对其进行序列化时,我的字符索引最终回到了 0。有人能看出我的错误吗?
BinaryFormatter binForm = new BinaryFormatter();
//check load data file and add new player to the list if char limit is not reached
using (FileStream fs = File.Open("./saves/loadData.vinload", FileMode.Open))
{
PlayerLoadData pLoad = (PlayerLoadData)binForm.Deserialize(fs);
Debug.Log(pLoad.charIndex);
if (pLoad.charIndex < 15)
{
pLoad.names[pLoad.charIndex] = finalName;
pLoad.charIndex += 1;
/*
Debug.Log(pLoad.charIndex);
foreach(string n in pLoad.names)
{
Debug.Log(n);
}*/
binForm.Serialize(fs, pLoad);
}
else
{
manifestScenePopups.TooManyChars();
return;
}
}
与BinaryFormatter
无关。您应该在创建 FileStream
时使用 FileMode.Create
选项
Specifies that the operating system should create a new file. If the file
already exists, it will be overwritten
using (FileStream fs = File.Open("d:\temp\a.txt", FileMode.Create))
编辑
您应该分两步完成。使用 FileMode.Open
反序列化。然后使用 FileMode.Create
覆盖现有数据。
我创建了一个加载文件来按顺序跟踪游戏中创建的所有角色。有 15 个字符的限制,因此每当玩家创建新角色时,我都需要检查是否达到了该限制。但是,当我尝试修改加载文件中的对象容器并再次对其进行序列化时,我的字符索引最终回到了 0。有人能看出我的错误吗?
BinaryFormatter binForm = new BinaryFormatter();
//check load data file and add new player to the list if char limit is not reached
using (FileStream fs = File.Open("./saves/loadData.vinload", FileMode.Open))
{
PlayerLoadData pLoad = (PlayerLoadData)binForm.Deserialize(fs);
Debug.Log(pLoad.charIndex);
if (pLoad.charIndex < 15)
{
pLoad.names[pLoad.charIndex] = finalName;
pLoad.charIndex += 1;
/*
Debug.Log(pLoad.charIndex);
foreach(string n in pLoad.names)
{
Debug.Log(n);
}*/
binForm.Serialize(fs, pLoad);
}
else
{
manifestScenePopups.TooManyChars();
return;
}
}
与BinaryFormatter
无关。您应该在创建 FileStream
FileMode.Create
选项
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten
using (FileStream fs = File.Open("d:\temp\a.txt", FileMode.Create))
编辑
您应该分两步完成。使用 FileMode.Open
反序列化。然后使用 FileMode.Create
覆盖现有数据。