Search Unity

Saving game state

Discussion in 'Scripting' started by -RaganorK-, Apr 24, 2017.

  1. -RaganorK-

    -RaganorK-

    Joined:
    May 9, 2014
    Posts:
    14
    Hi, I know this question is asked many times by now. But I am still confused in many levels. I am developing a simple resource management game and I want to resume the game in the state it was quit. I experimented with few plug-ins but either they were not working as expected, or were too complex to understand and implement.
    Basically I want to develop a Star Chef, My Cafe type game engine, where the game starts as it was quit last time. All instantiated objects, values and modified game objects. Can someone please guide me in the right proper direction ? I am already lost and, also, I don't have much time to experiment now.

    Thanks a lot in advance.
     
  2. Taorcb

    Taorcb

    Joined:
    Mar 15, 2015
    Posts:
    39
    Simple values for money and happiness levels, or any more that you'd want, can be stored in a simple class and serialized and deserialized to JSON via Unity's JsonUtility class. I'd suggest something like this:

    Code (CSharp):
    1. [System.Serializable]
    2. public class SaveData {
    3.      public float something;
    4.      public float somethingElse;
    5.  
    6.      public string serialized {
    7.           get {
    8.                return JsonUtility.ToJson(this);
    9.           }
    10.      }
    11.  
    12.      public SaveData Deserialize(string json) {
    13.           return JsonUtility.FromJson<SaveData> (json);
    14.      }
    15. }
    Note that any serializable class needs to have the [System.Serializable] tag, and JsonUtility can only serialize public variables. For instantiated objects, I'd make them all prefabs, save a reference to them or perhaps a Resources directory link, save their positions, rotations, and all other relevant data in a JSON class similar to the one above, and instantiate them with the saved positions and rotations when you need to.

    I tend to compile small JSON representations of individual things into an array on a larger class and serialize that, so that I can stick everything into one unintelligible text file for saving. You may want to go a different route, use PayerPrefs perhaps, or send them to a server or something. Most of the implementation will depend on how your game is structured.