Trying to reference a node after a scene change

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By pbij

I have a set of code in an autoload script whose purpose is to update the visuals of my inventory slots.
Problem is that when I change scenes the node’s path changes and this code no longer works.

func _update_slot_visual(slotIndex, item_name, new_quantity):
	var slot = get_tree().root.get_node("/root/Home/UserInterfaceGroup/Inventory/InventoryContainer/Slot" + str(slotIndex))
	if slot.item != null:
		slot.item._set_item(item_name, new_quantity)
	else:
		slot._initialize_item(item_name, new_quantity)

The path /root/Home/UserInterfaceGroup/Inventory/InventoryContainer/Slot changes to /root/Level1/UserInterfaceGroup/Inventory/InventoryContainer/Slot when the scene changes.

I was hoping that changing the line to this would work, but it just comes up null:

var slot = get_tree().root.find_node("/root/*/UserInterfaceGroup/Inventory/InventoryContainer/Slot" + str(slotIndex))
:bust_in_silhouette: Reply From: Pomelo

You can either use a Format String, or just join strings together with the + operator. For example using the plus:

var level_path = "/level8"
var correct path = "/root" + level_path + "/UserInterfaceGroup/..."

with the format string:

var format_path = "/root/%s/UserInterfaceGroup/..."
var actual_path = format_path % "level8"

In both cases you would need to pass the data of which level you are on of course.

Thanks, I’ll try this.

pbij | 2022-09-13 14:20