Scriptableobject Inventory System Clear OnDisable & Save

Hi, I’m trying to get my inventory objects in the array to clear and then save to maybe an INI file or something. I was from Gamemaker Studio and I used INI. I’m not sure how to do it in Unity. The codes you’re seeing here is me trying to take what worked in Gamemaker for me previously and port it into Unity. But… I’m not sure if this is the right way.

using UnityEngine;

[CreateAssetMenu(fileName = "New Inventory", menuName = "Inventory System/Inventory")]
public class InventoryObject : ScriptableObject
{
    public int inventorySlots = 8;
    public InventorySlot[] slot;

    public void OnEnable()
    {
        slot = new InventorySlot[inventorySlots];

        // TODO: Load from externally.
    }

    public void OnDisable()
    {
        // TODO: Save externally.
    }

    public void AddItem(ItemObject _item, int _amount)
    {
        for (int i = 0; i < slot.Length; i++)
        {
            if (slot[i].item == _item)
            {
                slot[i].AddAmount(_amount);
                break;
            }
            else
            {
                slot[i].AddItemAmount(_item, _amount);
                break;
            }
        }
    }
}

[System.Serializable]
public class InventorySlot
{
    public ItemObject item;
    public int amount;
    public InventorySlot(ItemObject _item, int _amount)
    {
        item = _item;
        amount = _amount;
    }

    public void AddAmount(int value)
    {
        amount += value;
    }

    public void AddItemAmount(ItemObject _item, int value)
    {
        item = _item;
        amount += value;
    }
}

Generally ScriptableObjects are for predefined data that you create as separate asset instances in your project. You actually CAN use them for anything, but they do NOT get OnEnable/OnDisable calls the way you expect them to: the lifecycle of a ScriptableObject is subtly different from a Monobehavior.

I think what you want is a Monobehavior and to put it in an inventory Scene (or on a Prefab) and make your Inventory that way. That way when you disable that object (or unload or destroy it), you will receive OnDisable() calls. I highly recommend using a Scene rather than a Prefab for something as complex as an inventory system, and then additively loading it, and then unloading it when dismissed.

2 Likes

Thanks man! Ok, I’ll try to change things up accordingly.