A simple save system in Unity

Saving game data is a task that I need regularly. Using serialization and writing data to a file is an approach that I have used much, but that does not work in WebGL builds. Instead, I wrote data in a PlayerPrefs string. In this way I do not need to keep a details about what objects have a save data to delete or find all save data. The XML string stored contains everything.

All objects that should be saved needs to inherit PersistentObject interface and implement a function PersistentObject.Save(). Save should use ObjectManager.SaveInt(), SaveString() or SaveVector() functions to add data to be saved. In Start() function, one reads data and call ObjectManager.RegisterPersistentObject(this) and read the save data; to notify ObjectManager that the class instance wants to be saved. Then save points needs to call ObjectManager.SavePersistent() to save data to PlayerPrefs string. See an example at the end of the post.

Public functions

SaveExists(): returns true if there the game has save data.

SaveInt(string k, int d): adds an int d to be saved, k is the key to get the data (k needs to be unique).

SaveString(string k, string d)

SaveVector3(string k, Vectro3 d)

string GetString(string k, string def=””): returns string with key k or def value if there is no value matching the key.

int GetInt(string k, int def=0)

Vector3 GetVector3(string k): returns Vector3 with key k. NegativeInfinity is returned if there is no data matching the key.

Just attach the ObjectManager script to a game object (a scene should have one ObjectManager).

For example, if one wants to save position and rotation of the object following code will do that for the object it is attached to:

publicclass SavePositionRotation:MonoBehaviour,PersistentObject{voidStart(){ObjectManager.RegisterPersistentObject(this);Vector3p=ObjectManager.GetVector3(name+"_p");Vector3r=ObjectManager.GetVector3(name+"_r");if(!float.IsInfinity(p.x)){transform.position=p;transform.eulerAngles=r;}
// else use the original position of the gameObject
}voidPersistentObject.Save(){ObjectManager.SaveVector3(name+"_p",transform.position);ObjectManager.SaveVector3(name+"_r",transform.eulerAngles);}}

Note that the name of the gameObject is used as the main part of the save key here. An implication of this is that all objects saved needs to have an unique name.