Best way of saving game data?

I have an inventory with different variables. It also have a bunch of child’s with there own variables. I would like to simple call a save methoud that lookes somthing like this:
save(GameObject gameObject, string path)

Then all the scripts and the child’s scripts would save.

and then load it with this methoud:
load(GameObject gameObjectToLoad, string path)

Then all the scripts and the child’s scripts would load.

I don’t know how to achieve this tho. I have found two different save systems: BinaryFormatter and XMLSerializer. None of those can serialize components or gameobjects which is the problem. So what should I use?

Thanks for your help! Just tell me if you need any more info.

You could just use the JSON serializer.

You could use a struct with a [Serializable] attribute for saving/loading data.

Here’s a (long) article on serialization in general in Unity: Unity Blog

Or for something easier to digest, a tutorial: Recorded Video Session: Quiz Game 2 - Unity Learn

1 Like

Can you give some more information as gameobjects can’t be serialized with jsonutitilty. Is it possible to save a prefab in runtime to a place on the computer? It seems to be easier to work with prefabs as they can store all the gameobject’s data.

Create your prefabs at design time. I suggest either putting them in a Resources folder or assigning them all to a “manager” component so you can reference them.

To save your inventory, make a list of all the items’ GameObject names and serialize it using something like JsonUtility, which can serialize strings. Rough example:

[Serializable]
public class InventoryItems {
    public List<string> itemNames;
}

// Save:
var inventoryItems = new InventoryItems();
inventoryItems.itemNames = new List<string>();
foreach (var item in playerInventory.items) {
    inventoryItems.itemNames.Add(item.name);
}
PlayerPrefs.SetString("save", JsonUtility.ToJson(inventoryItems));

To load your inventory, retrieve your InventoryItems and go through the list instantiating items:

var inventoryItems = JsonUtility.FromJson<InventoryItems>(PlayerPrefs.GetString("save"));
foreach (var itemName in inventoryItems.itemNames) {
    playerInventory.items.Add(Instantiate(Resources.Load(itemName)));
}
1 Like

Thank you

Glad to help!

1 Like