Find_child won't find child that is added during game

Godot Version

4.2

Question

here are the two functions in my code:

func _on_setting_menu_swap():
	if self.find_child("scene_auto"):
		print("get game")
		for scene in self.find_child("scene_auto").get_children():
			if scene is CanvasLayer:
				scene.visible = true
                    # there are many canvas layer under scene_auto which is also a canvas layer
                    # so i can only use this dum way to make it visible again
		return
		# if game scene is already added, don't return to main menu
	else:
		print("get main menu")
		self.find_child("menu_UI").visible = true
func _on_start_pressed():
	$color/AnimationPlayer.play("fade_in")
	$color/ColorRect.mouse_filter = 0
    # a transition, doesn't really matter
	var scene = scene_auto.instantiate()
	scene.set_process(false)
    # the process is set true after the transition animation and it works
	add_child(scene)

however, when I run the game, dispite the remote node shows that the scene with name “scene_auto” is added as the child of main scene:
image
when _on_setting_menu_swap() method is called. it still can’t find scene_auto and return null. which result in main menu been displayed.
Is there a way to solve this?

1 Like

Adding nodes at runtime gives them auto generated names which are not what you’re expecting them to be.

I would suggest using a signals to tell the parent nodes what is going on rather than using find everywhere, but if you really want to use find you can determine what the autogen name looks like and use wildcard patterns instead of the exact name.

how can I determine what the auto generated node name look like?

Well you already know how to add a node. Do you think perhaps there might be a way to find out what the node’s name is after you’ve added it? Did you try looking that up in the documentation? Did you try experimenting with the code?

I have tried scene.name = “scene_auto” but find_child still can’t find it. Also in the above screenshot shows the node in remote mod when the scene is added. Which does display the name I want but can’t be find

for people finding the same issue and find this question. the way to solve it is change find_child(“the name of the node”) into find_child(“the name of the node”, true, false). this is because somehow when a node is added as the child node of another node, its onwer is still null. So you must change the method such that it searches for all node instead of the nodes child node

1 Like

Just stumbled upon this.

Another solution is to set the owner after adding the Node as child:

parent.add_child(_placeable_component, true)
_placeable_component.set_owner(parent)

This way, a default find_child("name") works.

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