Saving/Loading gameobject name in .dat file

Hi guys!

I have 3 instantiated gameobjects with names I wish to save to a .dat file, so I can load them back at any point:


All of which has the below script attached.

However, instead of saving all the names of the objects and placing them back, it only saves the last object’s name and replaces that name to all the objects that has the script attached.

Here’s the code I have so far:

using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

public class saveFile : MonoBehaviour {

	class playerData
		public string name;

	public void Save()
		BinaryFormatter binary = new BinaryFormatter();
		FileStream file = File.Create(Application.persistentDataPath +"/SaveGame.dat"); 
		playerData dat = new playerData(); =;                      

		binary.Serialize(file, dat);

	void Awake()
		if (File.Exists(Application.persistentDataPath + "/SaveGame.dat"))
			BinaryFormatter binary = new BinaryFormatter();
			FileStream file = File.Open(Application.persistentDataPath + "/SaveGame.dat", FileMode.Open);

			playerData dat = (playerData)binary.Deserialize(file);

            //this sets all the saved data back onto gameobject
			name =; 

The problem is that each object will be serialized in turn (apparently it is not asynchronous or you would have received errors during serialization).

As each object is serialized in turn, they are going to create a brand new “SaveGame.dat” file, and it will overwrite the file that the previous object had created. The last object to get serialized will then be the “winner” and when de-serialization, all objects will have the last object’s name and properties. Recreating the file each time is just overwriting the last serialized object’s properties.

You will want to find a different approach to serialize your data. One way to do this would be to put the actual serialization script not onto each object, but perhaps on a parent object or even some other object (like maybe a serialization manager) instead.

You can create a collection of objects which you can add the those you wish to serialize (you could use tags to select them as well), then have your save operation collect all of them and then save them out in one fell swoop.