BinaryFormatter没有对象的映射



我序列化了我的对象,并将其放在unity中的Resources文件夹中。我的游戏应该将此文件复制到Application.persistentDataPath路径并进行反序列化。我收到错误:Failed to serialize. Reason: No map for object '201326592'.

我的"复制";代码:

public void CopyAndDeserialize()
{
saveData.itemsOfClothing = new List<ItemsOfClothingData.ItemOfClothing>();
TextAsset resourcesTextData = (TextAsset)Resources.Load("items");
path = Path.Combine(StorageManager.Instance.GlobalPath + _saveFileName);
if(!File.Exists(path))
{
File.Create(path);
}
File.WriteAllText(path, resourcesTextData.text);
DeserializeData();
}

反序列化数据:

public void DeserializeData()
{
path = Path.Combine(StorageManager.Instance.GlobalPath + _saveFileName);
if (File.Exists(path))
{
fileStream = new FileStream(path, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
try
{
saveData = (ItemsOfClothingData)binaryFormatter.Deserialize(fileStream);
}
catch (SerializationException e)
{
MonoBehaviour.print("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fileStream.Close();
}
fileStream.Close();
}
}

谢谢你的帮助!

文件不是二进制格式,请使用System.IO.File.ReadAllLines(string filepath)System.IO.File.ReadAllText(string filepath)正确读取。

有关详细信息,请参阅Microsoft文档:https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=net-6.0

已解决问题。使用Resource.Load<TextAsset>(path).bytes获取字节数组,并像往常一样进行反序列化。

最新更新