How to find an instanced scene by its name?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By teedoubleu
:warning: Old Version Published before Godot 3 was released.

If I want to find a node by its name I usually do get_tree().get_root().find_node(), but it doesn’t work for instanced scenes, even if they are placed in the tree in the editor.

Whats the reason behind making it to work like that? I often create new scenes from branches of the main scene and suddenly all code dependent on find_node() stops working because its not a node I’m looking for, but an instanced scene.

:bust_in_silhouette: Reply From: avencherus

Possibly a bug, you might want to report or ask in the Github issues.

Otherwise you could work around it with something like this (though this returns the first name match it finds):

func _ready():

	var node = find_node_by_name(get_tree().get_root(), "my_node_name")
	if(node): printt(node, node.get_name())

func find_node_by_name(root, name):

	if(root.get_name() == name): return root

	for child in root.get_children():
		if(child.get_name() == name):
			return child

		var found = find_node_by_name(child, name)

		if(found): return found

	return null
:bust_in_silhouette: Reply From: volzhs

First of all, try to use Remote Inspector to see what scene tree actually is made.

then I guess, you can see the name of instanced node is something like @block@155 like screenshot above.
you should set a specific, non-conflict name to instanced node if you want to find it by find_node
if you set it as same name with another which is already in scene tree and same depth, it will be renamed to something unique.

só para complementar. Assim que você faria para mudar o nome:

    myInstance = preObj.instance()
	myInstance.set_name("myInstanceName")
	add_child(myInstance)

PerduGames | 2017-11-11 22:08

:bust_in_silhouette: Reply From: manusiatidakbiasa

What I do is adding it to a group and use get_nodes_in_group to call it

for example I have a Player scene. I added it to group “player”

to get player I do

var player = (get_tree().get_nodes_in_group(“player”))[0]

:bust_in_silhouette: Reply From: Artium Nihamkin

Please try the following and report back if it resolved the issue:

get_tree().get_root().find_node("BlaBla", true, false)

Setting owned to false solved similar problems I had.

with “owned = false” works, what does this “owned” does?

PerduGames | 2017-11-11 23:19