|
|
|
|
|
|
using System.Collections.Generic; |
|
|
|
using UnityEngine; |
|
|
|
using UnityEngine; |
|
|
|
public class SaveSystem : MonoBehaviour |
|
|
|
public class SaveSystem : ScriptableObject |
|
|
|
public delegate void AddToRegistryCallback(HashSet<ISaveable> registry); |
|
|
|
|
|
|
|
public static AddToRegistryCallback AddToRegistry; |
|
|
|
public LocationDatabase locationDatabase; |
|
|
|
[SerializeField] private LoadEventChannelSO _loadLocation = default; |
|
|
|
HashSet<ISaveable> _saveRegistry = default; |
|
|
|
public string saveFilename = "save.chop"; |
|
|
|
public Save saveData = new Save(); |
|
|
|
const string SAVE_FILENAME = "save.chop"; |
|
|
|
void OnEnable() |
|
|
|
{ |
|
|
|
_loadLocation.OnLoadingRequested += CacheLoadLocations; |
|
|
|
} |
|
|
|
private void Start() |
|
|
|
void OnDisable() |
|
|
|
Debug.Log("SaveSystem start getting called"); |
|
|
|
_saveRegistry = new HashSet<ISaveable>(); |
|
|
|
AddToRegistry?.Invoke(_saveRegistry); |
|
|
|
LoadGame(); |
|
|
|
_loadLocation.OnLoadingRequested -= CacheLoadLocations; |
|
|
|
private void LoadGame() |
|
|
|
private void CacheLoadLocations(GameSceneSO[] locationsToLoad, bool showLoadingScreen) |
|
|
|
if (FileManager.LoadFromFile(SAVE_FILENAME, out var json)) |
|
|
|
LocationSO locationSo = locationsToLoad[0] as LocationSO; |
|
|
|
if (locationSo) |
|
|
|
Save saveData = new Save(); |
|
|
|
saveData.LoadFromJson(json); |
|
|
|
|
|
|
|
foreach (ISaveable saveable in _saveRegistry) |
|
|
|
{ |
|
|
|
saveable.Deserialize(saveData); |
|
|
|
} |
|
|
|
saveData._locationId = locationSo.DescId.uuid; |
|
|
|
private void SaveGame() |
|
|
|
public void LoadGame() |
|
|
|
// A class with name "Save" must exist in the project. It will contain the appropriate save file structure.
|
|
|
|
Save saveData = new Save(); |
|
|
|
foreach (ISaveable saveable in _saveRegistry) |
|
|
|
if (FileManager.LoadFromFile(saveFilename, out var json)) |
|
|
|
saveable.Serialize(saveData); |
|
|
|
saveData.LoadFromJson(json); |
|
|
|
} |
|
|
|
if (FileManager.WriteToFile(SAVE_FILENAME, saveData.ToJson())) |
|
|
|
public void SaveGame() |
|
|
|
{ |
|
|
|
if (FileManager.WriteToFile(saveFilename, saveData.ToJson())) |
|
|
|
} |
|
|
|
|
|
|
|
private void OnDisable() |
|
|
|
{ |
|
|
|
SaveGame(); |
|
|
|
} |
|
|
|
} |