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.
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)));
}