Hi yall, I need help understanding why this code doesn’t work. When trying to access my inventory (which is an array) through the get_item() method the array is always empty, but when adding them through the add_item() method my debugging line is always showing the correct inventory. How can the same array that’s declared globally in the same script return different two different arrays depending on the method that called it??
1 - if inventory[i] != null
this code is problematic. not the issue here but it’s going to cause issues.
for checking if an object exists you have to do
is_instance_valid() or just inventory[i] which should evaluate to true if it exists.
2 - for i in range(inventory_size)
is also problematic.
get the size from inventory so it’s correct, otherwise you can forget to update inventory_size and get an error.
or set inventory_size in add_item.
or make it local to add_item.
3 - the array appears to hold dictionaries.
use get to get values from a dictionary, otherwise you will run into an error. inventory[i].get("type", 0) #if the dictionary doesn't have "type", it will return 0
4 - you need to create a new dictionary or duplicate it to assign it to a different location of an array, otherwise you are reusing the same dictionary and passing a reference to it.
5 - this doesn’t seem to be the source of the problem. you need to see where get_item and add_item are called and where the dictionary is defined and assigned, and every place where it is changed.
by globaly you mean it’s an autoload? because THAT’S the only way to make it global.
if it’s in your script, each node with that script assigned is a different object with their own versions of the variables.