- Home /
Save inventory items
So I'm working on a simple inventory system, that instantiates selected items as children of the slots GameObjects. And now I want to save those items, and all I can come up with is getting a list of the items names and saving them, as references to the items, then load them from the Resources one by one. I was wondering if there is a better way to save and load the items. Here is a glimpse of the inventory script:
string dir = "Slot";
slot [n] = GameObject.Find (dir+i).transform as RectTransform;
if (slot [n].GetComponentInChildren<Equip> ()) {
n++;
if (n >= slot.Length) {
picking = false;
full = true;
}
}else if (!slot [n].GetComponentInChildren<Equip> ()) {
ToEquip = true;
ToPickUp = false;
GameObject go = Instantiate (items, new Vector3 (0, 0, 0), slot [n].transform.rotation) as GameObject;
go.transform.parent = slot [n];
go.transform.localPosition = new Vector3 (0, 0, 0f);
TextTarget = slot [n].GetComponentInChildren<Text> ();
TextTarget.text = name;
Destroy (gameObject);
Debug.Log ("Item Added To inventory");
}
Answer by Axtrainz · Aug 05, 2017 at 01:37 AM
Whenever I need to save objects such as list or any kind of collection I use [Serializable] tag on a class and save it with Binary Format. Example:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using UnityEngine;
public class SaveInventory
{
public List<Item> inventory = new List<Item>();
//To save inventory to file. Use static for quick access
private void save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/Inventory.dat");
Inventory toSaveInventory = new Inventory();
toSaveInventory.inventory = this.inventory;
bf.Serialize(file, inventory);
file.Close();
}
//To load inventory from file. Use static modifier for quick access
private void load()
{
if (File.Exists(Application.persistentDataPath + "/Inventory.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/Inventory.dat", FileMode.Open);
Inventory InventoryLoaded = (Inventory)bf.Deserialize(file);
file.Close();
this.inventory = InventoryLoaded.inventory;
}//if
}//load function
//To load inventory from file with returns. Use static modifier for quick access
private List<Item> load()
{
if (File.Exists(Application.persistentDataPath + "/Inventory.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/Inventory.dat", FileMode.Open);
Inventory InventoryLoaded = (Inventory)bf.Deserialize(file);
file.Close();
return InventoryLoaded.inventory;
}//if
return new List<Item>();
}//load function
}//class
[Serializable]
class Inventory
{
//save a list of *item* type. this can be string, int and all type of data, See List<T> documentations C# or (Java if it helps).
public List<Item> inventory;
}
Notes: Make sure your inventory to save has the same values of the saved one before saving it. I'll leave you that as homework.
Regards.
hi, how can I create this save system?
[Item.cs] using UnityEngine;
[CreateAsset$$anonymous$$enu] public class Item : ScriptableObject { public Sprite sprite; public GameObject gameObject; public string interactable; } /**/ [Inventory.cs]
using UnityEngine; using UnityEngine.UI;
public class Inventory : $$anonymous$$onoBehaviour { public Image[] itemImages = new Image[numItemSlots]; public GameObject[] itemGameObjects = new GameObject[numItemSlots]; public Item[] items = new Item[numItemSlots]; public string[] itemIntercatable = new string[numItemSlots]; public SaveInventory saveInventory = new SaveInventory();
public const int numItemSlots = 8;
private Interactable interactable;
public Button button;
public void AddItem(Item itemToAdd)
{
for (int i = 0; i < items.Length; i++)
{
if (items [i] == null)
{
items [i] = itemToAdd;
itemImages [i].sprite = itemToAdd.sprite;
itemGameObjects [i] = itemToAdd.gameObject;
itemIntercatable[i] = itemToAdd.interactable;
saveInventory.items[i] = itemToAdd;
saveInventory.save();
itemImages [i].enabled = true;
return;
}
}
}
public void RemoveItem(Item itemToRemove)
{
for (int i = 0; i < items.Length; i++)
{
if (items [i] == itemToRemove)
{
items [i] = null;
itemImages [i].sprite = null;
itemGameObjects [i] = null;
itemIntercatable[i] = null;
itemImages [i].enabled = false;
return;
}
}
}
}
Hi, As there is only a save/load function you can do add/remove/change functions.
as Example: on SaveInventory Class add the following..
//to add new Item
public void addItem(Item item)
{
// syncronize file with current inventory object.
//after checking if everything is syncronized..
//addItem
inventory.add(item);
save(); // to re syncronize files and objects.
}
//To Remove an Item
public bool addItem(string itemId)
{
// syncronize file with current inventory object.
//after checking if everything is syncronized..
//remove Item with linear search - Binary search is recommended.
int index = 0;
foreach(Item item in inventory)
if(item.id == itemId)
{
//we get the item by unique id.
index = inventory.IndexOf(item); // we get index of the matching item to avoid the duplicate items.
inventory.RemoveAt(index)
save(); // to re syncronize files and objects.
return true;
}
return false;
}
These are examples for add, remember to put as [Serializable] the Item Class. if need something else contact me. Regards
Better if you post it as a comment. Note: [Serializable] does not support inheritance, polymorphism.
Answer by agray427 · Jan 15, 2018 at 05:53 PM
I just finished writing a post on my blog that talks about serializing Item data and supports polymorphism. I recommend checking it out as a solution for your stuff as well. It also talks about the importance of separating data from the interface which will definitely help with serializing. https://graymattertutorials.wordpress.com/2018/01/15/serialization-with-json-net-in-unity-3d/