Variable not saving after leaving for loop

Godot 4.2

My problem is that the variable doesnt safe, after leaving the for loop it becomes null again.
The Script is of the Autoload Script for the Inventory Manager.

extends Node

@export var inv: Inventory = load("res://Inventorys/Inv9Slots.tres")

func PickupItem(item:Item):
	for slot in inv.Slots:
		if slot == null:
			slot = item.duplicate()
			inv = inv.duplicate()
			print_debug(slot.ItemName) #returns the items Resource's var ItemName -> the Variable for the item is there
		elif slot.ItemName == item.ItemName && slot.CurrentStack != slot.MaxStackSize:
			slot.CurrentStack += 1
			inv = inv.duplicate()
	print_debug(inv.Slots[0].ItemName) #returns ERROR because the variable of the Item is missing

This is probably because you’re never assigning anything to inv.Slots[0] (at least not in the code above). slot = item.duplicate() just changes the local variable slot to a reference to the new item copy, that doesn’t change the Slots array or what items are in it.

Also, why are you replacing the entire inv Inventory reference with a new copy with inv = inv.duplicate() for each slot in the inventory?

1 Like

okay that makes sense, but how would i go about assingning it? i thought thats how you would do it.

i was just trying some random stuff to somehow fix it. it indeed is not necesary.

okay i used an i counting up like in classical for loops and its working but i dont think its the most elegant way.

Edit: nvm i was just to dumb to use the for loops in Godot, thought they behaved differently from other languages somehow

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.