/// <summary> /// Create save game file and save Savable Objects /// </summary> /// <param name="saveName"></param> public static void Save(string saveName) { KS_SaveGame save = new KS_SaveGame { SceneIndex = SceneManager.GetActiveScene().buildIndex }; // Call event to add data before serialization if (OnSave != null) { OnSave(ref save.SaveData); } // Setup binary selector and surrogates BinaryFormatter bf = new BinaryFormatter(); SurrogateSelector ss = new SurrogateSelector(); AddSurrogates(ref ss); bf.SurrogateSelector = ss; // Save all Savable objects to file foreach (GameObject obj in GetAllObjects()) { save.gameObjects.Add(StoreObject(obj)); } // Serialize save object MemoryStream stream = new MemoryStream(); bf.Serialize(stream, save); // Save save object to file KS_FileHelper.Instance.SaveFile(Folders.Saves, saveName + GetFileFormat(), stream.GetBuffer()); }
/// <summary> /// Load save game /// </summary> /// <param name="name">Name of the file (excluding file format)</param> /// <returns></returns> public static KS_SaveGame Load(string name) { BinaryFormatter bf = new BinaryFormatter(); SurrogateSelector ss = new SurrogateSelector(); AddSurrogates(ref ss); bf.SurrogateSelector = ss; MemoryStream stream = new MemoryStream(); byte[] file = KS_FileHelper.Instance.LoadFileToBytes(Folders.Saves, name + GetFileFormat()); stream.Write(file, 0, file.Length); stream.Position = 0; KS_SaveGame save = (KS_SaveGame)bf.Deserialize(stream); if (OnLoad != null) { OnLoad(save); } return(save); }