Godot Version
v4.2.1
Question
I’ve been working on an inventory system for my RPG following some YouTube tutorials, and I’m trying to make it so that my items menu adds or subtracts item slots to match the number of different items that are in the player’s inventory. This would prevent the cursor from being able to go to a bunch of empty slots with no items, potentially scrolling the menu into a screen with no items. Here’s my ‘inventory’ script:
extends Resource
class_name Inv
signal update
signal new_item_obtained
signal item_count_depleted
@export var slots : Array[InvSlot]
func insert(item : InvItem):
var item_slots = slots.filter(func(slot): return slot.item == item)
if !item_slots.is_empty():
item_slots[0].quantity += 1
else:
var empty_slots = slots.filter(func(slot): return slot.item == null)
if !empty_slots.is_empty():
empty_slots[0].item = item
empty_slots[0].quantity = 1
else:
slots.resize(slots.size() + 1)
empty_slots = slots.filter(func(slot): return slot.item == null)
empty_slots[0].item = item
empty_slots[0].quantity = 1
update.emit()
My thought was to basically say if the item is already in the inventory, add 1 to its quantity - this works. Then, if the item is not already in the inventory, check for empty slots and if there is one, put the item there and make its quantity 1 - that part works as well. The problem is when I say if there are no empty slots, resize the array by adding 1 to its size and then put the item in the resulting empty slot. The error that pops up says that after the resize there’s an Invalid index .item on base Nil. Could anyone explain to me what is happening and/or how to fix it? Happy to provide any other info as well.