Last active
January 19, 2018 13:31
-
-
Save buijldert/357e7554885a85f6a2a93f589129fae4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using UnityEngine; | |
using System.Runtime.Serialization.Formatters.Binary; | |
namespace Serialization | |
{ | |
public class Serializer | |
{ | |
public static void Save<T>(string filename, T data) where T : class | |
{ | |
using (Stream stream = File.OpenWrite(Application.persistentDataPath + "/" + filename)) | |
{ | |
BinaryFormatter formatter = new BinaryFormatter(); | |
formatter.Serialize(stream, data); | |
stream.Close(); | |
} | |
} | |
public static T Load<T>(string filename) where T : class | |
{ | |
if (DoesFileExist(filename)) | |
{ | |
try | |
{ | |
using (Stream stream = File.OpenRead(Application.persistentDataPath + "/" + filename)) | |
{ | |
BinaryFormatter formatter = new BinaryFormatter(); | |
return formatter.Deserialize(stream) as T; | |
} | |
} | |
catch (Exception e) | |
{ | |
Debug.Log(e.Message); | |
} | |
} | |
return default(T); | |
} | |
public static void DeleteSave(string filename) | |
{ | |
if(File.Exists(Application.persistentDataPath + "/" + filename)) | |
{ | |
File.Delete(Application.persistentDataPath + "/" + filename); | |
} | |
} | |
public static bool DoesFileExist(string filename) | |
{ | |
if (File.Exists(Application.persistentDataPath + "/" + filename)) | |
return true; | |
else | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment