I'm trying to serialize / deserialize a class that holds inventory items.
The code is attached below.
First I call AddOne()
void a few times, then I call SaveFile()
, then I call LoadFile()
.
In LoadFile()
the following error occurs :
ex = "System.Runtime.Serialization.SerializationException: End of Stream encountered before parsing was completed.\r\n at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run () [0x00288] in <1f0c1ef1ad524c38bbc5536809c46b48>:0 \r\n at System.Runt...
Does anybody see my mistake?
Thank you for the help!
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public enum Type
{
undefined = 0,
Pistol = 1,
Magnum = 2,
Grenade = 3,
BlendGrenade = 4,
FireGrenade = 5,
PistolAmmo = 6,
MagnumAmmo = 7,
Rifle,
RifleAmmo,
}
[System.Serializable]
public class Inventory : MonoBehaviour
{
public class InventoryItem
{
public int Amount = 0;
public int Row = 0;
public int Col = 0;
public int Rotation = 0;
public Type ItemType = Type.undefined;
}
public List<InventoryItem> Items;
public void Start()
{
Items = new List<InventoryItem>();
}
public void AddOne()
{
InventoryItem n = new InventoryItem();
this.Items.Add(n);
}
public void SaveFile()
{
string destination = Application.persistentDataPath + "/save3.dat";
if (File.Exists(destination))
{
File.Delete(destination);
}
using (Stream stream = File.Open(destination, FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, this.Items);
}
}
public void LoadFile()
{
string destination = Application.persistentDataPath + "/save3.dat";
using (Stream stream = File.Open(destination, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
try
{
this.Items = (List<InventoryItem>)bin.Deserialize(stream);
}
catch (Exception ex)
{
Debug.Log(ex.ToString());
}
}
}
}