Categories How To

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

All codes are available for free Here:

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

You can watch me explain it all, line by line, here:

I researched many different ways to create storage systems. Many tutorials recommend using Unity PlayerPrefs files. The file is really there to store user settings preferences and things like that so using it to store seems more like a hack than anything.

I thought about using the JSON utility built into Unity but that also raised a big problem for me: The objects you save must have public fields. I prefer to keep my classes well encapsulated (Separate from anything that shouldn’t be touched or isn’t related to its function/data), so I chose Microsoft’s built-in IO (input output) namespace.

You will use StreamWriter and StreamReader for saving and loading respectively. The examples here cover a lot of what you need to know.

The strategy I use to store my inventory involves searching for all Items in my project using the Resources.FindAllObjectsOfType method () Unity. I put each item into a code and put all the codes and items into the dictionary.

When saving inventory, I’ll write an item code (hashed using Animator.StringToHash) concatenate characters to split the code and count that item, and combine the counts.

For Load, each line in the save file is read. The lines are separated based on the character that separates them in the writing process, and the first part of the separated line is the item code and the second part is the count. The string is parsed back into an integer, and the Item code is put into a dictionary I created earlier with all the item codes and related items to get the item.

When we get each item and its item number, we add them to a second dictionary (the return value from the Load method) and pass them back to the inventory where the inventory can choose what to do with the dictionary – (like adding them to the inventory).

I leave it to the reader to decide how to store inventory. In my case, I did it in the built-in OnDisable callback that is in all MonoBehaviours. You can do this on the button’s onClick event – ​​Since this is a public method, you can put the SaveInventory script into the slot that appears in the inspector when you add the onClick event to the Button component.

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

Game Online

Gaming Hub

A gaming hub can refer to a central platform or space dedicated to gaming, where players can access games, interact with other gamers, and enjoy related content.

More From Author