
Two static methods which allow game data to be saved to file in a binary format. Works on all platforms except web, as webplayer can’t save to file. The c# Serializer used is cross platform, but it cannot serialize UnityEngine.Object, or anything extending UnityEngine.Object, which includes ScriptableObject and GameObject
#region Save/Load
//using System.Runtime.Serialization.Formatters.Binary;
//using System.IO;
public static bool SaveData(object Data, string FileName)
{
BinaryFormatter bf = new BinaryFormatter();
string computedFileName = Application.persistentDataPath + "/" + FileName;
FileStream file = null;
try
{
file = File.Create(computedFileName);
bf.Serialize(file, Data);
return true;
}
catch (System.Exception ex)
{
Debug.Log("SaveGame Failed :" + computedFileName + "" + ex.Message);
}
finally
{
if (file != null) {
file.Close();
file.Dispose();
}
}
return false;
}
public static bool LoadData<T>(out T Data, string Filename) where T : class
{
string computedFileName = Application.persistentDataPath + "/" + Filename;
Data = default(T);
if (File.Exists(computedFileName))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = null;
try
{
file = File.Open(computedFileName, FileMode.Open);
Data = bf.Deserialize(file) as T;
return Data != default(T);
}
catch (System.Exception ex)
{
Debug.Log("LoadGame failed :" + computedFileName + "" + ex.Message);
return false;
}
finally
{
if (file != null) {
file.Close();
file.Dispose();
}
}
}
else
{
Debug.Log("LoadGame, File does not exist :" + computedFileName);
}
return false;
}
#endregion
Data provided to SaveData() is serialized to binary, and written straight to file. LoadData() deserializes whatever binary data it loads from file into an object, which is cast to the type you provide and returned. As the methods returns a boolean, out parameters are used. Application.persistentDataPath is a built-in Unity value that always holds the location of a writable path on whatever platform you are on (web excluded), generally Filename can be anything, but it is recommended to add a file extension.
Code adapted from Unity Live Training video.
[Serializable] attribute needs to be added to any class that will be saved via serialization.

One thought on “Unity : Cross Platform Compatible Save Data”
I had trouble with this code working on my iPod, where it worked fine on the android version.