Skip to content

Instantly share code, notes, and snippets.

@Nordaj
Last active September 16, 2018 15:06
Show Gist options
  • Save Nordaj/cc33d758fd5a566d673dceb0399c80b3 to your computer and use it in GitHub Desktop.
Save Nordaj/cc33d758fd5a566d673dceb0399c80b3 to your computer and use it in GitHub Desktop.
Use this unity script to save and load data. It will work with any serializable type.
using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public static class DataManager
{
private static Dictionary<string, object> data;
/// <summary>
/// Necessary to call at the start of the program!
/// _None_ will load no data
/// False is returned on fail
/// </summary>
public static bool Init(string loadDirectory = "_None_")
{
data = new Dictionary<string, object>();
//Check if im using directory
if (loadDirectory == "_None_")
return true;
//Fail if loadDirectory does not exists
if (!File.Exists(loadDirectory))
return false;
//Load to data
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Open(loadDirectory, FileMode.Open);
data = (Dictionary<string, object>)bf.Deserialize(fs);
fs.Close();
//Return success
return true;
}
/// <summary>
/// Destroys the file in given directory
/// </summary>
/// <param name="directory"></param>
public static void DestorySave(string directory)
{
File.Delete(directory);
}
/// <summary>
/// Gets value of type T from key
/// </summary>
public static T Get<T>(string key)
{
if (data.ContainsKey(key))
return (T)Convert.ChangeType(data[key], typeof(T));
else
return default(T);
}
/// <summary>
/// Gets value of type T from key
/// </summary>
public static void Get<T>(string key, ref T val)
{
if (data.ContainsKey(key))
val = (T)Convert.ChangeType(data[key], typeof(T));
else
val = default(T);
}
/// <summary>
/// Check if a key exists
/// </summary>
public static bool Check(string key)
{
return data.ContainsKey(key);
}
/// <summary>
/// Adds a value of type T
/// </summary>
public static void Set<T>(string key, T value)
{
if (data.ContainsKey(key))
data[key] = value;
else
data.Add(key, value);
}
/// <summary>
/// Don't forget to save!
/// </summary>
public static void Save(string saveDirectory)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Create(saveDirectory);
bf.Serialize(fs, data);
fs.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment