Friday, December 27, 2019

Unity3D JSON Serialization (save game data)


Let's keep this short:
My BoxingDay activity was to create a small Unity3d project utilizing JSON serialization for saving game data. Basically, this sample project shows how to save and load game data in one serializable class.

Whole project is available at Github:
https://github.com/jliias/SaveData
(I believe it should work as such)



In this sample project I will serialize GameData class, that contains following variables:
bool adsEnabled
int coinsCollected
int highScore

These variables are packed and unpacked to text format using JsonUtility API that can be used to convert Unity objects to and from JSON format. Basically, it is possible to pack and unpack simple objects to text format by using this API (e.g. collections or arrays are not supported).

Serializing to JSON is done using ToJson method, and and deserializing using FromJson method.

It is important to add [Serializable] to the top of class that will be serialized.

This is very simple solution and as far as know this should be pretty easy to modify for your own purposes. I am going to use this for example in upcoming "Flamingo Tap Tap Run" game update, that is planned to be released in Jan 2020.

-Jussi

No comments:

Post a Comment