- Home /
Some help with saving and loading in Unity
I'm reading up on how to save and load in Unity, and I'm having a little trouble understanding it. Thus far, I understand that data must be serialized. But let's say you have a class called "Enemy," and that class stores variables for the enemy object's position, rotation, and health. How do you serialize this class for multiple enemies? And when you load the data, how do you know which data goes to which enemy?
Sorry if this is a stupid/misguided question, but I'm very new to saving and loading.
Answer by Cherno · Sep 28, 2015 at 11:04 AM
First of all: I invite you to take a look at my SerializeHelper aset, it's free and is aimed at teaching the basics of datas serializing and saving/loading functionality for any game. You will spend a days just understanding it and reading up on topics on MSDN; there's no way around it. Serialization in combination with Unity is a fairly advanced and complex topic with numerous pitfalls. No quick and easy works-for-all solution there :)
The question you asked is answered by SerializeHelper. Basically, you have to go through all the GameObjects that need to have some of their data saved, and create a new instance of a container class for each which holds the data. This instance can then be added to a list or array and serialized. You also have to find a way to identify each GameObject between saving and loading so the right data can be given back to the right GameObject. SerializeHelper does this by generating a unique ID via GUID.
Thanks for your response! In your opinion, would it be better to simply use one of the Serializers provided by the Unity community rather than trying to code my own?
Let me put it this way:
Generally, there is no better way to learn than trying things out for yourself. However, it can't hurt to also look at how other people have done things. In the end, no asset provided to you will be an exact fit for the game you envision, there will always be the need for customization. When writing SerializeHelper, I started with simple serialization of simple data: some strings, some ints etc. However, in Unity, we have to deal with Unity-specific classes ($$anonymous$$onoBehaviors, Vector3, GameObjects and so on), and these require workarounds because they can not be serialized as-is. For some classes, this is relatively simple (although still a daunting task for someone with no experience), for others, less so. I got a good many ideas from the great "UnitySerializer", an asset that is sadly no longer supported but is still a treasure chest of information.
tl;dr: You may want to $$anonymous$$ch you the basics yourself by experimenting with some simple serialization operations, and once you go in deeper, you can use that knowledge to understamnd how other people have done it and go from there ins$$anonymous$$d of trying to figure out everything yourself.
Ok, I will keep that in $$anonymous$$d. Thanks very much :)