Get node after using .instance and add_child

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

When using:

var weapon = load("res://weapon.tscn")
var w = weapon.instance()
get_tree().get_root().get_node("Level/Player").call_deferred("add_child", w)

The game adds the node with weird version of the original name, instead of “weapon”, imports it by “@weapon@8” and cause error due to some get_node() functions

When I try to use

get_node("Level/Player/@weapon@8")

in the previous function, it imports it with the name of “weapon” for some reason. There’s a way to fix this? Thanks in advance.

:bust_in_silhouette: Reply From: timothybrentwood

Create an array of weapons or a weapon variable and a weapon pickup function in your Player script:

# Player.gd
var weapons = []
# OR: var current_weapon

func pickup_weapon(instance_of_weapon_to_pickup):
    call_deferred("add_child", instance_of_weapon_to_pickup)
    weapons.push_back(instance_of_weapon_to_pickup)
    # OR: current_weapon = instance_of_weapon_to_pickup

func get_last_picked_up_weapon():
    if not weapons.empty():
        return weapons.back()
    # OR: return current_weapon

Then your code becomes:

var weapon = load("res://weapon.tscn")
var w = weapon.instance()
get_tree().get_root().get_node("Level/Player").pickup_weapon(w)