I am not sure your problem is with the code you have posted. If your code is not working then the problem might be with the set_item()
function or with whatever is listening to the items_changed
signal.
There could also be a tree structure issue with item drop since it is adding a child to it's parent.
Staying within the code you have posted the problematic part is the add_item()
function. add_item()
is supposed to do 3 things:
- It checks if the
item
is already in items
(inventory?). This returns true
if successful.
- If
item
is not in items
then it tries to find an unassigned slot in items
to set as item
. This returns true
if successful.
- Return
false
if both previous steps fail.
If this is correct then here is what should change in the add_item()
code:
- Add
return false
at end of the function. There is currently no return value if item
is not in items
and items
is full. This is the only major issue with the function. As in it can cause crashes.
- If
return
is reached in the code, then the rest of the function is not executed. This can be used to simplify your code.
break
is written after return
and will never be reached. It can be removed.
Example:
func add_item(item):
for i in range(len(items)):
if items[i] != null:
if items[i].name == item.name:
emit_signal("items_changed" , [i])
return true
for i in range(len(items)):
if items[i] == null:
set_item(i, item)
emit_signal("items_changed", [i])
return true
return false
4 . You should consider using in build array functions. I would usefind()
in this case.
Example:
func add_item(item):
var i = items.find(item)
if i != -1:
emit_signal("items_changed" , [i])
return true
i = items.find(null)
if i != -1:
set_item(i, item)
emit_signal("items_changed" , [i])
return true
return false
The array.find(argument)
call returns the first index of the array
that matches argument
. If argument
is not found then find()
returns -1
.