Skip to content

Instantly share code, notes, and snippets.

@GeorgiyRyaposov
Last active August 5, 2017 10:42
Show Gist options
  • Save GeorgiyRyaposov/21ebbc73909730eb2001c00ca4f85923 to your computer and use it in GitHub Desktop.
Save GeorgiyRyaposov/21ebbc73909730eb2001c00ca4f85923 to your computer and use it in GitHub Desktop.
Save\load data with BinaryFormatter\json in Unity3d for builded game or in the editor
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
//to make BinarySerializer work at iOS devices add somewhere in awake:
//System.Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
namespace Assets.Scripts.Tools
{
public class DataManager
{
public DataManager(SerializerType serializerType)
{
switch (serializerType)
{
case SerializerType.Binary:
serializer = new BinarySerializer();
break;
case SerializerType.Json:
serializer = new JsonSerializer();
break;
default:
serializer = new JsonSerializer();
break;
}
}
public enum SerializerType
{
Binary,
Json
}
private readonly ISerializer serializer;
public void Save<T>(string fullFilePath, T data)
{
serializer.Serialize(fullFilePath, data);
}
public void SaveToPersistentData<T>(string fileName, T data)
{
serializer.SerializeToPersistentData(fileName, data);
}
public void SaveToResources<T>(string fileName, T data)
{
serializer.SerializeToResources(fileName, data);
}
public bool TryLoad<T>(string fullFilePath, out T result)
{
return serializer.TryDeserialize<T>(fullFilePath, out result);
}
public bool TryLoadFromPersistentData<T>(string fileName, out T result)
{
return serializer.TryDeserializeFromPersistentData<T>(fileName, out result);
}
public T LoadFromResources<T>(string fileName)
{
return serializer.DeserializeFromResources<T>(fileName);
}
}
public interface ISerializer
{
void Serialize<T>(string fullFilePath, T data);
void SerializeToResources<T>(string fileName, T data);
void SerializeToPersistentData<T>(string fileName, T data);
bool TryDeserialize<T>(string fullFilePath, out T result);
bool TryDeserializeFromPersistentData<T>(string fileName, out T result);
T DeserializeFromResources<T>(string fileName);
}
public class JsonSerializer : ISerializer
{
public void Serialize<T>(string fullFilePath, T data)
{
try
{
CreatePath(fullFilePath);
var json = JsonUtility.ToJson(data, true);
System.IO.File.WriteAllText(fullFilePath, json);
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();
#endif
}
catch (Exception e)
{
Debug.LogError("Failed to save data: " + e);
}
}
public void SerializeToPersistentData<T>(string fileName, T data)
{
var fullPath = string.Format("{0}/{1}.txt", Application.persistentDataPath, fileName);
Serialize<T>(fullPath, data);
}
public void SerializeToResources<T>(string fileName, T data)
{
var fullPath = string.Format("{0}/{1}/{2}.txt", Application.dataPath, "Resources", fileName);
Serialize<T>(fullPath, data);
}
public T Deserialize<T>(string fullFilePath)
{
if (!Path.HasExtension(fullFilePath))
{
fullFilePath += ".txt";
}
if (!File.Exists(fullFilePath))
{
Debug.Log("Nothing to load");
return default(T);
}
var text = File.ReadAllText(fullFilePath);
T data;
try
{
data = JsonUtility.FromJson<T>(text);
}
catch (Exception e)
{
Debug.LogError("Failed to deserialize. Reason: " + e.Message);
return default(T);
}
return data;
}
public T DeserializeFromResources<T>(string fileName)
{
var txtData = Resources.Load<TextAsset>(fileName);
if (txtData == null)
{
Debug.Log("Nothing to load");
return default(T);
}
T data;
try
{
data = JsonUtility.FromJson<T>(txtData.text);
}
catch (Exception e)
{
Debug.LogError("Failed to deserialize. Reason: " + e.Message);
return default(T);
}
return data;
}
public bool TryDeserialize<T>(string fullFilePath, out T result)
{
if (!Path.HasExtension(fullFilePath))
{
fullFilePath += ".txt";
}
if (!File.Exists(fullFilePath))
{
Debug.Log("Nothing to load");
result = default(T);
return false;
}
var text = File.ReadAllText(fullFilePath);
T data;
try
{
data = JsonUtility.FromJson<T>(text);
}
catch (Exception e)
{
Debug.LogError("Failed to deserialize. Reason: " + e);
result = default(T);
return false;
}
result = data;
return true;
}
public bool TryDeserializeFromPersistentData<T>(string fileName, out T result)
{
var fullPath = string.Format("{0}/{1}.txt", Application.persistentDataPath, fileName);
return TryDeserialize<T>(fullPath, out result);
}
private void CreatePath(string fullFilePath)
{
if (File.Exists(fullFilePath))
{
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(fullFilePath)); // create directory if it not exists
File.Create(fullFilePath).Dispose();
}
}
public class BinarySerializer : ISerializer
{
public void Serialize<T>(string fullFilePath, T data)
{
fullFilePath += ".bytes";
CreatePath(fullFilePath);
var fs = new FileStream(fullFilePath, FileMode.Create);
var formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, data);
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();
#endif
}
catch (Exception e)
{
Debug.LogError("Failed to serialize. Reason: " + e);
}
finally
{
fs.Close();
}
}
public void SerializeToPersistentData<T>(string fileName, T data)
{
var fullPath = string.Format("{0}/{1}", Application.persistentDataPath, fileName);
Serialize<T>(fullPath, data);
}
public void SerializeToResources<T>(string fileName, T data)
{
var fullPath = string.Format("{0}/{1}/{2}", Application.dataPath, "Resources", fileName);
Serialize<T>(fullPath, data);
}
public T Deserialize<T>(string fullFilePath)
{
if (!Path.HasExtension(fullFilePath))
{
fullFilePath += ".bytes";
}
if (!File.Exists(fullFilePath))
{
Debug.Log("Nothing to load");
return default(T);
}
var bytes = File.ReadAllBytes(fullFilePath);
T data;
try
{
var formatter = new BinaryFormatter();
using (var ms = new MemoryStream(bytes))
{
data = (T)formatter.Deserialize(ms);
}
}
catch (Exception e)
{
Debug.LogError("Failed to deserialize. Reason: " + e);
return default(T);
}
return data;
}
public T DeserializeFromResources<T>(string fileName)
{
var txtData = Resources.Load<TextAsset>(fileName);
if (txtData == null)
{
Debug.Log("Nothing to load");
return default(T);
}
T data;
try
{
var formatter = new BinaryFormatter();
using (var ms = new MemoryStream(txtData.bytes))
{
data = (T)formatter.Deserialize(ms);
}
}
catch (Exception e)
{
Debug.LogError("Failed to deserialize. Reason: " + e.Message);
return default(T);
}
return data;
}
public bool TryDeserialize<T>(string fullFilePath, out T result)
{
result = default(T);
if (!Path.HasExtension(fullFilePath))
{
fullFilePath += ".bytes";
}
if (!File.Exists(fullFilePath))
{
Debug.Log("Nothing to load");
return false;
}
var bytes = File.ReadAllBytes(fullFilePath);
try
{
var formatter = new BinaryFormatter();
using (var ms = new MemoryStream(bytes))
{
result = (T)formatter.Deserialize(ms);
}
}
catch (Exception e)
{
Debug.LogError("Failed to deserialize. Reason: " + e.Message);
return false;
}
return true;
}
public bool TryDeserializeFromPersistentData<T>(string fileName, out T result)
{
var fullPath = string.Format("{0}/{1}", Application.persistentDataPath, fileName);
return TryDeserialize<T>(fullPath, out result);
}
private void CreatePath(string fullFilePath)
{
if (File.Exists(fullFilePath))
{
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(fullFilePath)); // create directory if it not exists
File.Create(fullFilePath).Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment