using UnityEngine;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveManager
{
//these set the names for the directory and file name to be stored.
public static string directory = "SaveData";
public static string fileName = "MySave.txt";
public static void Save(SaveObject so)
{
//calling a binary formatter and saving it as a variable
BinaryFormatter bf = new BinaryFormatter();
//opening the data path to the file we are looking for and saving a new directory/filename
//in designated area
FileStream file = File.Create(GetFullPath());
//rewrite over the save if it exists already
bf.Serialize(file, so);
//close the data path to the file,else errors will occur
file.Close();
}
public static SaveObject Load()
{
if( SaveExists())
{
try
{
//Opens existing file path and deserializes the data from the BinaryFormatter
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(GetFullPath(), FileMode.Open);
SaveObject so = (SaveObject)bf.Deserialize(file);
file.Close();
return so;
}
catch(SerializationException)
{
Debug.Log("Failed to properly load file");
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static bool DirectoryExists()
{
return Directory.Exists( Application.persistentDataPath + "/" + directory);
}
private static string GetFullPath()
{
return (Application.persistentDataPath +"/" + directory + "/" + fileName);
}
}