using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; /// /// A class for holding all progress belonging to a user /// [Serializable] public class Progress { /// /// A helper class for handling the stored progress /// [Serializable] protected class DataEntry { /// /// The key, used to reference the data object /// public string key; /// /// The object, representated as a list of byte (which can be serialized) /// public List bytes = new List(); public DataEntry(string key, byte[] data) { this.key = key; this.bytes = new List(data); } } /// /// Entries in the Progress object /// [SerializeField] private List entries = new List(); /// /// Update the value of a certain key, /// or add a new value if the key was not present /// /// The type of the data to be added/updated /// The key, used for referencing the data /// The object of type /// true if successful, false otherwise public bool AddOrUpdate(string key, T data) { if (data == null) return false; DataEntry entry = entries.Find(x => x.key == key); // Hacky serialization stuff BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, data); if (entry != null) { entry.bytes.Clear(); entry.bytes.AddRange(ms.ToArray()); } else { entries.Add(new DataEntry(key, ms.ToArray())); } return true; } } // Get the value of type `T` belonging to `key` /// /// Get the data object of a certain key /// /// The type of the data object /// The key referencing the data object /// The data, cast to a type /// public T Get(string key) { BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // Find the correct key foreach (DataEntry entry in entries) { if (entry.key == key) { // Hacky serialization stuff byte[] data = entry.bytes.ToArray(); ms.Write(data, 0, data.Length); ms.Seek(0, SeekOrigin.Begin); return (T)bf.Deserialize(ms); } } } // Raise an exception when key is not found throw new KeyNotFoundException(); } }