SerializationException errors!! & IOException. BinaryFormatter problems
after following the a unity tutorial I keep getting these SerializationException errors...
SerializationException: Type 'PlayerData' in Assembly 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
IOException: Sharing violation on path C:\Users\my PC\AppData\LocalLow\DefaultCompany\newscene\playerInfo.dat
SerializationException: End of Stream encountered before parsing was completed.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class saveStuff : MonoBehaviour
{
public static saveStuff control;
[SerializeField]
public int health;
void Awake()
{
if (control == null)
{
DontDestroyOnLoad(gameObject);
control = this;
}
else if(control != this)
{
Destroy(gameObject);
}
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData() { };
data.health = health;
Debug.Log("Save");
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
health = data.health;
file.Close();
Debug.Log("LOAD");
}
else
{
Debug.Log("no file found! :-( ");
}
}
}
[SerializeField]
public class PlayerData
{
public int health;
}
what's going on??? I've tried making it work for all day but i can't figure it out!?
Answer by ThomLaurent · Jan 04, 2020 at 07:22 AM
The serialization exception you get gives you hints about what's going wrong, see :
SerializationException: Type 'PlayerData' [...] is not marked as serializable.
You should replace the [SerializeField] field attribute in :
[SerializeField]
public class PlayerData
//...
by the [System.Serializable] class/struct attribute :
[Serializable]
public class PlayerData
//...
For the IOException I guess the file.Close() is not reached due to the other exception, so if you fix the first you fix the second.
This exception happens when you read or write on a file that is still open.
Note : Private fields of a Serializable class/struct are not serialized by default, with the [SerializeField] attribute you force a field serialization.
Hope it helps :)