Created
January 16, 2022 18:21
-
-
Save morphingcoffee/9af9d0b2dc17bda3f1cf27de2e361f97 to your computer and use it in GitHub Desktop.
"CI QuickSave" package-based saving in C# Unity, using IPersistable interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using UnityEngine; | |
using CI.QuickSave.Core.Storage; | |
/** | |
* Central place for triggering game saving & loading. | |
* Classes using [QuickSave] package will end up writing files at [Application.persistentDataPath]: | |
* MacOS: ~/Library/Application\ Support/DefaultCompany/<productname>/QuickSave | |
* Windows: %userprofile%\AppData\LocalLow\<companyname>\<productname> | |
**/ | |
public class SaveManager | |
{ | |
// Prevent creating multiple instances | |
private SaveManager() { } | |
public static void SaveGame() | |
{ | |
Debug.Log("Triggering Game Save"); | |
// 1. Save state for Unity objects | |
var unityPersistables = GameObject.FindObjectsOfType<MonoBehaviour>().OfType<IPersistable>(); | |
foreach (IPersistable persistable in unityPersistables) | |
{ | |
persistable.Save(); | |
} | |
// 2. Save state for other known (non-Unity) persistables | |
((IPersistable)QuestManager.Instance).Save(); | |
((IPersistable)Inventory.Instance).Save(); | |
// ... | |
} | |
public static void LoadGame() | |
{ | |
Debug.Log("Triggering Game Load"); | |
// 1. Load state for other known (non-Unity) persistables | |
((IPersistable)Inventory.Instance).Load(); | |
((IPersistable)QuestManager.Instance).Load(); | |
// ... | |
// 2. Load state for Unity objects | |
var unityPersistables = GameObject.FindObjectsOfType<MonoBehaviour>().OfType<IPersistable>(); | |
foreach (IPersistable persistable in unityPersistables) | |
{ | |
try | |
{ | |
persistable.Load(); | |
} | |
catch (Exception e) | |
{ | |
Debug.LogError("Loading of Game failed with: " + e.Message); | |
} | |
} | |
} | |
public static void DeleteGame() | |
{ | |
foreach (string fileName in FileAccess.Files(includeExtensions: true)) | |
{ | |
FileAccess.Delete(fileName, includesExtension: true); | |
} | |
} | |
public static bool HasSavedGame() | |
{ | |
return FileAccess.Files(includeExtensions: true) | |
.GetEnumerator() | |
.MoveNext(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment