Error with Inventory Size and the saving system

On the Inventory.cs we have on ISaveable.RestoreState

 var slotStrings = (string[])state;          
 for (int i = 0; i < inventorySize; i++)
 {
   slots[i] = InventoryItem.GetFromID(slotStrings[i]);
 }

Lets imagine you give an inventory size of 4 and then save.
Then you modify the value in your Inspector, to a greater number like 20.
Then Play. The game crash immediatly, because we will try to to access index that don’t exist on the array slotStrings. We introduce a difference between the size of the two arrays (inventorySize and slotStrings).

There is two solutions. Put back the old value of the inventorySize if you remenber it, Play, and then Delete the save (or delete the save file manually).
Or use this change of code.

            int arrayLength = inventorySize;
            if (slotStrings.Length < inventorySize)
            {
                arrayLength = slotStrings.Length;
            }
            for (int i = 0; i < arrayLength; i++)
            {
                slots[i] = InventoryItem.GetFromID(slotStrings[i]);
            }

The game won’t crash, but if you do the opposite manipulation (putting a lower inventory size than the saved one) … well yours items after the new inventory size are not reloaded.

1 Like

You’re quite right, we didn’t plan here for dynamic inventory sizes.

This is a good solution for this.

1 Like

Privacy & Terms