Saving assigned game objects

Hello everyone, I need to make a saving system for our game. I’ve made different saving systems with Unity before so I’m not that new to saving but now I have a problem. I need to be able to save the game objects (prefabs) that are assigned to variables in scripts.
So let’s say that during game runtime I got variables:
var1 = prefabA;
var2 = prefabB;
var3 = prefabC;

How can I save the information about which prefabs are assigned to the different variables?

Serialization.

Unity Answers post

Stramit just posted a great post on serialization.

Thanks, I will have a look and if Ihave any questions, I’ll ask here :slight_smile:

Well I have a problem already.
I read many articles about serializing and started to construct something in JS.
Now, from what I read in the documentation, when defining a class I don’t need to add “@Serialize” before the class and neither do I need to add “@SerializeField” before my classes variables because they are all public.

So I have a custom class called Ship. I made another class called “ProgressHold” to hold the game info that needs to be serialized. One of the components of the class is a Ship variable and when trying to serialize that variable I get an error saying:

My code for saving is:

function Save(){
        //the game data that will be saved. The player variable is of type Ship
	var gameData : ProgressHold = ProgressHold(level, player, money, purchasedShips, purchasedTurrets, turrets);
	var	stream : Stream = File.Open(Application.dataPath + "/file.ext", FileMode.Create);
	var bf : BinaryFormatter = new BinaryFormatter();
	bf.Serialize(stream, gameData);
	stream.Close();
}

Got rid of the problem. Turns out a lot of classes cannot be serialized. Had to translate a lot of things into simple int, float and String variables for the serialization to work.

It saves well but now I have another problem:

function Load(){
	var stream : Stream = File.Open(Application.dataPath + "/file.ext", FileMode.Open);
	var bf : BinaryFormatter = new BinaryFormatter();
	var data = bf.Deserialize(stream);
	stream.Close();
}

It won’t load anything back. No error is thrown just nothing happens. Those are both functions in a class of type GameState.
I have an object of this class (gs) and I reach the functions like that:

gs.Save();
gs.Load();

When I tell it to save it creates a file with the extension and puts information in it successfully but when I try to load the information back nothing happens. I read somewhere that every time I run the game Unity generates a new key for the Binary Formatter but I couldn’t understand more :confused:

Got this one too. I get the data from the binary formatter but never use it. Since I serialize a GameState object, the data variable is a GameState type object so I just have to return it.