Generic Serialiser Class

It’s been a busy month what with one thing and another, so I haven’t managed to get finished the UNET custom NetworkHUD tutorial I’ve been working on, but I’ll post it as soon as I can.

In the meantime I’ve been doing some groundwork for an RPG idea we’ve had, and one of the first requirements is for an easy way to save and load the state of the various data classes we’ll be using. As this is something that also seems to get asked for on a fairly regular basis in the forums, I thought I’d share what I’ve come up with so far as it might prove useful to others in some situations.

The serialiser as it currently stands is quite simple, it has four static methods, two for serialising the data (one to PlayerPrefs and one as binary data), and two that read in the data and return it in an instance of the corresponding class.
It will serialise any class or struct that is marked as Serialisable and it even works with dictionaries.

This is the code for the serialiser class.

As an example, to save the state of a class to PlayerPrefs you would use something like this:-

To load the data back into the program you would use something like this:-

The way I actually tend to use it though is to wrap the serialiser calls into two methods on the class I want to serialise. An instance method for saving, and a static method for loading the data, which returns an instance of the class populated with the data.

So for example, i might define a PlayerInfo class something like this:-

And then from elsewhere in the program I would load and save the class data like so:-

The Load() function automatically handles the situation where there is no saved data yet, and returns a new instance of the class in that case.

I have made a simple demonstration program that allows you to type in a player name and add and remove items from the inventory. When you exit and restart the program you will see that the changes you made will have been preserved.

Using this generic serialiser it becomes a simple task to save and load even quite complex classes and structs, as long as you remember to mark them as serialisable.

Also remember that if you make any changes to the serialised class definition after you have saved it, you will most likely have to delete the saved data to avoid errors when it tries to load it next.

I hope this proves to be of use to someone, and as always any comments and suggestions are welcome.

You can try out the test program in a Unity WebPlayer here or download the project files here.

See you soon

Martin.