access a node's child by name, not path or index

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

I want to access a node’s child using that child’s name and NOT it’s path or it’s index if that is possible.

for example:
node.get_child(child’s_name_no_quotes).queue_free()

or
var player = get_parent() #acquire the desired name

name = player # change the name of a child in a different node to be the same as the player, like giving it an ID that is special and accessible from other nodes using it’s ID.

one thing that also bugs me is that when you use get_node, you have to put the argument in quotes, and the argument has to be a node path?. wouldn’t that make it impossible to put a variable in quotes without it turning into whatever was quoted?

1 Like
:bust_in_silhouette: Reply From: avencherus

Not exactly.

get_node() takes a path which is a NodePath type, which behaves like a String.

The closest thing to what you want is the shorthand $, but it will need quotes if you use spaces in your node names.

$my_node or with spaces $"my node"

For manipulating paths with variables you concatenate as you need.

for i in 10:
	get_node(str("node_", i))

If you want to use some other method you can collect up the node references and store them in a Dictionary, using the key as the identifier you prefer.

onready var node_table = {
	
	1 = get_node("thing"),
	2 = get_node("thing/child_1"),
	2 = get_node("thing/child_2")
}

You could also create constants with the paths, so these can be updated quickly from the top of your script.

const FIRST = "thing_1"
const SECOND = "thing_1/child_1"

if(has_node(FIRST)):
	get_node(FIRST)

Nodes also instance IDs, but these are entirely fixed as you develop, and the tracking of these can be more verbose and prone to error.

Objects have the method get_instance_id().
GSCript has the utility function instance_from_id .

thanks for the response.
Is it possible to use get_node() when I want to access an instanced child?

func _on_Area_area_entered(area):
    var a_name = area.get_parent().get_parent().name #the parent of the area
    print(a_name)  #would print: Player
    if $'a_name':      #trying to search children with the same name as area.
    pass   #already have a child with the name
   else:       #don't have a child with the name
      var new_child = instanced_node.instance()
      self.add_child(new_child)
      new_child.set_name(a_name)    

beginner, very lost here sorry

witch_milk | 2020-12-01 17:22

Just a quick correction on the “Dictionary” solutions:

onready var node_table = {

    1 : get_node("thing"),
    2 : get_node("thing/child_1"),
    3 : get_node("thing/child_2") 
}

Changes: “=” (assign) changed to “:”, numeration was wrong (1,2,2 changed to 1,2,3)

Might seem dumb but could help newbies

Gianclgar | 2022-05-15 21:47