A while back I was working on a simple Unity project that needed the ability to save and load highscore data. The most common solution I've found other developers implement is to create and manage a set of PlayerPrefs keys in their projects. For me, I like having a custom external file that I can access with other C# utilities should I want to inspect and compare the contents of save files during development. With that in mind, here is a simple serialization script for Unity and a very simple project to demonstrate how it works.
I've created a simple project in Unity with 2D format. In the scene is a Cube, three buttons, a point light, and a pair of scripts. One script is used to manage the colour of the cube and the other is the SaveLoadBehaviour script which will handle our "game data":
|Hierarchy for the scene|
Both scripts - SaveLoadBehaviour and ColourBehaviour - are attached to the Cube object out of convenience. The buttons each call SendMessage on ColourBehaviour, each sending the string "Red", "Green", or "Blue" as appropriate.
The ColourBehaviour script is relatively simple:
|The Start method checks for a save file to set the cube colour, defaulting to red|
|Colour setting methods - they also call the SaveGameData method|
Speaking of GameData:
|GameData is a struct with a string representing the most recent colour of the cube|
The save and load methods are very simple:
|The SaveGameData and LoadGameData methods|
|It will still be a blue cube when the scene is next played|
So that's how vanilla serialization can be used to make save files in Unity. As long as the [Serializable] tag is applied, more complex objects can be handled without any changes to the methods. A github link to the example Unity project is below but please note that accessing the SaveLoadBehaviour's object from the outside is poor practice and that the filepath for saving is currently hardcoded - this is fine for a simple project with just one save file, but for multiple save files there will be some additional functionality required.
Here's the github link: https://github.com/AdamBoyce/UnitySaveLoadExample
I hope this is helpful to someone out there, and thanks for reading.