Skip to content

Instantly share code, notes, and snippets.

@0xdw
Created April 16, 2021 05:39
Show Gist options
  • Save 0xdw/3595f7cc6527d59689a16c22e2d34065 to your computer and use it in GitHub Desktop.
Save 0xdw/3595f7cc6527d59689a16c22e2d34065 to your computer and use it in GitHub Desktop.
Unity - Reading and writing binary file (Save file)
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
namespace Utility {
public static class BinaryDataStream {
private static readonly string Path = Application.persistentDataPath + "/saves/";
private const string Ext = ".dat";
public static void Save<T>(T data, string fileName) {
Directory.CreateDirectory(Path);
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(GetFullPath(fileName), FileMode.Create);
try {
formatter.Serialize(stream, data);
} catch (SerializationException e) {
Debug.Log("Save failed. Error: " + e.Message);
} finally {
stream.Close();
}
}
private static string GetFullPath(string fileName) {
return Path + fileName + Ext;
}
public static bool Exists(string fileName) {
return File.Exists(GetFullPath(fileName));
}
public static T Read<T>(string fileName) {
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(GetFullPath(fileName), FileMode.Open);
T returnType = default(T);
try {
returnType = (T) formatter.Deserialize(stream);
} catch (SerializationException e) {
Debug.Log("Read failed. Error: " + e.Message);
} finally {
stream.Close();
}
return returnType;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment