Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Save game architecture question - onSaveGame event

Discussion in 'Scripting' started by dhenion65, Jun 14, 2020.

  1. dhenion65

    dhenion65

    Joined:
    Dec 17, 2019
    Posts:
    21
    I'm working on a game that includes crafting - so the player can create things in-game. I finally got around to making a save/load game system and it works great - BUT - I'm wondering if I've built it in a way that could lead to problems later.

    To me it doesn't make sense for all objects to constantly be updating their save game data all the time. Yea its great its all there and ready at save game time, but seems like a lot of overhead going on all the time when not saving.

    So instead I have the save game manager clear all the data and send out a onUpdateSaveData event that all objects listen to. Every object then makes a call in to the save data class to insert their data, after which all the data gets written out to a file.

    Code (csharp):
    1.     public void SaveGame()
    2.     {
    3.         // clear out any current data in save data
    4.         SaveData.current.ObjectList.Clear();
    5.         SaveData.current.AllSavedInventories.Clear();
    6.         // tell all in-scene objects to update their save data
    7.         onUpdateSaveData.Invoke();
    8.         // update player info in save data - more to add later
    9.         SaveData.current.PlayerPosition = Player.transform.position;
    10.         SaveData.current.PlayerRotation = Player.transform.rotation;
    11.         // save out the data
    12.         SerializationManager.Save("testSaveFile", SaveData.current);
    13.         ResumeGame();
    14.     }
    So far this is working perfectly - but the first thing I thought of is that I don't really know when all the objects are done putting their data in to the SaveData class. For now when testing I've got maybe a few dozen objects, but later there could be hundreds.

    Is this a bad approach? Is there a better way to have all objects update their save data before a save?
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Depending on how your game works, I would likely use an interface. Have each saveable object implement the said interface and add itself to a list when enabled and remove itself when disabled. I would then iterate through that list to call a method and create the save data.
     
    ADNCG likes this.
  3. dhenion65

    dhenion65

    Joined:
    Dec 17, 2019
    Posts:
    21
    Yes good idea and wasn't hard to implement - thank you, seems more robust this way.