Unity has ways to save game data like PlayerPrefs but it is quite limited and can store information in strange locations on certain platforms. In this post, I’ll demonstrate a more object oriented approach that allows you to save almost any kind of data structure to a file. This method is going to be based off of how Unreal Engine 4 handles saving games.
To start, we’ll create a SaveGame object that will be used as an abstract base class for all of our saved game objects. This class is marked as [Serializable] so that C# is able to serialize it, and it’s also marked as abstract because we won’t be using it directly to save games.
Next comes the static SaveGameSystem class that does most of the heavy lifting of saving, loading, and deleting save files.
The SaveGame method takes a SaveGame object and a name, and saves it to a file. The LoadGame method takes a name and loads the file back into a usable SaveGame object. The DeleteGame method takes a name and deletes the associated save game file. All of these methods use GetSavePath to determine where the save game file should be located. By default, it’s saved to the Application.persistantDataPath which is different on each platform. On Windows, it should be located somewhere similar to C:\Users\[username]\AppData\LocalLow\[companyname]\[projectname]. If you want to customize the saved game location, just modify this method.
Finally, create a custom class to store save game data that will be written to a file. This class should be marked as [Serializable] and inherit from the SaveGame class. It should contain any fields you wish to save to a file. By default C#‘s BinaryFormatter class serializes all public and private fields, and public and private properties. To prevent a field from being serialized, it should be marked with the [NonSerialized] attribute.
Below is an example of how you could use this system to save and load a saved game.
// Saving a saved game.
// Loading a saved game.
// Deleting a saved game.
I think this approach is much better than using PlayerPrefs because of its added flexibility, and hopefully you do as well. If you have any further questions please feel free to message me on Twitter @RyanNielson or comment below.