Categories Gaming

How to Save and Load in Unity (Specifically using an Inventory)


All the code is available for free here:

Specifically we want to look at – /blob/master/Assets/Scripts/Inventory/InventorySaveSystem.cs

You can watch me explain everything, line by line, here:

I researched a lot of different ways for creating a save system. A lot of tutorials recommend using the Unity PlayerPrefs file. That file is really there to save a user’s settings preferences and stuff like that so using it to save seems more like a hack than anything.

I thought about using the JSON utility built in to Unity but that too poses a major problem for me: The objects you’re saving have to have public fields. I prefer to keep my classes well encapsulated (Separate from anything that shouldn’t be touching or isn’t related to their functionality/data), so I opted for Microsoft’s built in IO (input output) namespace.

You’ll be using the StreamWriter and StreamReader to save and load, respectively. The examples here, cover a lot of what you need to know.

The strategy I used for saving my inventory involved finding all the Items in my project using Unity’s Resources.FindAllObjectsOfType <T> () method. I hashed each item into a code and put all the codes and items into a dictionary.

When saving the inventory, I would write the item’s code (hashed using Animator.StringToHash) concatate a character to split the code and count of that item, and concatate the count.

To Load, each line in the save file is read. The lines are split by the character that split them in the writing process, and the first part of the split line is the item code and the second part the count. Those strings were parsed back to integers, and the Item code was fed into the dictionary I created earlier with all the item codes and corresponding items to get the item.

As we get each item and the number of that item, we add them to a second dictionary (the return value of the Load method) and pass that back to the inventory where the inventory could choose what to do with that dictionary – (like add them to the inventory).

I leave it up to the reader to decide how to save the inventory. In my case, I do it in the built-in OnDisable callback that exists on all MonoBehaviours. You could do it on a button’s onClick event – Since it’s a public method, you could drop the SaveInventory script into the slot that appears in the inspector when you add an onClick event to a Button component.

Hopefully this helps; leave any questions in the comments (better on YouTube than here).



Game Online

Gaming Hub

More From Author