I am trying to save & load inventory items (a game object). The problem is that my
items are a bit complex.
This is what variables the inventoryitem
has
// paste code here
and this is what the itemData
(scriptable object) has
// paste code here
As development goes on I’ll probably end up adding more variables to them.
- Is there a way to just save the items or do we need to save all the primitive variables
and reconstruct the gameObject, via prefabs and what not?
- if I were do it through prefabs, I need to preload all potential prefabs (could be hundreds)
by dragging them into the editor. that’s a lot of memory.
Is there a way to load them at run time to make it less expensive?
I’d love to know if there’s a better approach. This method just seems so inefficient to me.
I’d assume that all those variables are defined per type of the item, not per instance of the item (as saved in your inventory). So why don’t you create a ScriptableObject that holds these variables (feel free to call it ItemData, or ItemType), then in your savegame, just reference the ItemType instance and number of stacked objects, wear, or whatever per-instance variables.
To reference a ScriptableObject in a savegame, you need some way to serialize this reference. A good way is to have some sort of lookup / dictionary in another ScriptableObject, and use its Key. So for example you’d have classes
class ItemType : ScriptableObject
{
public SlotTypes slotType;
public string displayName;
public Sprite image;
.....
public string Id => this.name;
}
class ItemCollection : ScriptableObject, ISerializationCallbackReceiver
{
[SerializeField] private List<ItemType> m_itemTypes;
[SerializeField] private Dictionary<string, ItemType> m_itemTypesDict;
void ISerializationCallbackReceiver.BeforeSerialize() {}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
m_itemTypesDict.Clear();
// Here, add all m_itemTypes to m_itemTypesDict, use ItemType.Id as Key
}
public bool TryGetItem(string id, out ItemType itemType) => m_itemTypesDict.TryGetValue(id, out itemType);
}
When loading / saving, obtain your instance of ItemCollection, and translate between the Id and actual ItemType reference.