Data Persistence System - UO-DFM/SimCityOttawa-Documentation GitHub Wiki

This system is adapted from https://www.youtube.com/watch?v=aUi9aijvpgs&list=LL&index=1&ab_channel=TreverMock

Enabling your class to save data

In order to allow your monobehavior to save and load its local state it must implement the IDataPersistence interface. I contains just two methods.

LoadData will be called by the DataPersistenceManager on load and provide you with the GameData found on disk, otherwise it will contain the default value.

Here you should 're-hydrate' the local state of your class with the appropriate data found in GameData.

public void LoadData(GameData data){
    this.transform.position = data.playerPosition;
}

SaveData will be called on Save. The DataPersistence Manager will provide your class with a reference of the GameData to be saved. Here you must modify the GameData to store your current state.

public void SaveData(ref GameData data){
    data.playerPosition = this.transform.position
}

Ex.

public class DeathCountText : MonoBehaviour, IDataPersistence
{
    private int deathCount = 0;

    private TextMeshProUGUI deathCountText;


    public void LoadData(GameData data) 
    {
        this.deathCount = data.deathCount;
    }

    public void SaveData(GameData data) 
    {
        data.deathCount = this.deathCount;
    }
}

Next, the values you store in GameData must be defined in the GameData class itself as public variables.

In the constructor you must initialize these values with the default values you wish to use when there is no save data.

Ex.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class GameData
{
    public int deathCount;
    public Vector3 playerPosition;
    public SerializableDictionary<string, bool> coinsCollected;

    // the values defined in this constructor will be the default values
    // the game starts with when there's no data to load
    public GameData()
    {
        this.deathCount = 0;
        playerPosition = Vector3.zero;
        coinsCollected = new SerializableDictionary<string, bool>();
    }
}

Triggering New, Load, and Save Data Events

The DataPersistenceManager is a globally accessible singleton and thus can be accessed by any other MonoBehaviour within the scene.

It exposes three public methods NewGame(), LoadGame() and SaveGame() which do as their namesake suggests.

Ex.

public class MainMenu : MonoBehaviour{
    public void OnNewGameClicked(){
        DataPersistenceManager.Instance.NewGame();
    }

    public void OnLoadGameClicked(){
        DataPersistenceManager.Instance.LoadGame();
    }

    public void OnSaveGameClicked(){
        DataPersistenceManager.Instance.SaveGame();
    }
}