Hi,
I followed along to the course but unfortunately I now have a broken save system. When I press S to save I get the message:
SerializationException: End of Stream encountered before parsing was completed.
Can you please help? I have copied the exact files from the resource GItHub. When I double click on the error it navigates to the file “SavingSytem.CS” and goes to line:
Dictionary.
Code below,
Thanks,
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace RPG.Saving
{
public class SavingSystem : MonoBehaviour
{
public IEnumerator LoadLastScene(string saveFile)
{
Dictionary<string, object> state = LoadFile(saveFile);
int buildIndex = SceneManager.GetActiveScene().buildIndex;
if (state.ContainsKey("lastSceneBuildIndex"))
{
buildIndex = (int)state["lastSceneBuildIndex"];
}
yield return SceneManager.LoadSceneAsync(buildIndex);
RestoreState(state);
}
public void Save(string saveFile)
{
Dictionary<string, object> state = LoadFile(saveFile);
CaptureState(state);
SaveFile(saveFile, state);
}
public void Load(string saveFile)
{
RestoreState(LoadFile(saveFile));
}
public void Delete(string saveFile)
{
File.Delete(GetPathFromSaveFile(saveFile));
}
private Dictionary<string, object> LoadFile(string saveFile)
{
string path = GetPathFromSaveFile(saveFile);
if (!File.Exists(path))
{
return new Dictionary<string, object>();
}
using (FileStream stream = File.Open(path, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
return (Dictionary<string, object>)formatter.Deserialize(stream);
}
}
private void SaveFile(string saveFile, object state)
{
string path = GetPathFromSaveFile(saveFile);
print("Saving to " + path);
using (FileStream stream = File.Open(path, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, state);
}
}
private void CaptureState(Dictionary<string, object> state)
{
foreach (SaveableEntity saveable in FindObjectsOfType<SaveableEntity>())
{
state[saveable.GetUniqueIdentifier()] = saveable.CaptureState();
}
state["lastSceneBuildIndex"] = SceneManager.GetActiveScene().buildIndex;
}
private void RestoreState(Dictionary<string, object> state)
{
foreach (SaveableEntity saveable in FindObjectsOfType<SaveableEntity>())
{
string id = saveable.GetUniqueIdentifier();
if (state.ContainsKey(id))
{
saveable.RestoreState(state[id]);
}
}
}
private string GetPathFromSaveFile(string saveFile)
{
return Path.Combine(Application.persistentDataPath, saveFile + ".sav");
}
}
}