Signal when child is added to node.

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

Forgive me if this exists, but I couldn’t find any way to detect when a child is added to a node. For example, say I have a top-level node that affects all of its children. I want certain functions in the parent to be called on any child that is added to it. Is there a way to accomplish this?

:bust_in_silhouette: Reply From: neikeq

Node has notifications NOTIFICATION_PARENTED and NOTIFICATION_UNPARENTED. This is an usage example:

func _notification(what):
	if what == NOTIFICATION_PARENTED:
		prints("Now I am a child of", get_parent().get_name())
	elif what == NOTIFICATION_UNPARENTED:
		print("I have been orphaned")

About the parent, I did not find a signal nor a notification for child added, but you could achieve that by overriding add_child:

func add_child(node):
	.add_child(node)
	prints("I just fathered", node.get_name())

And you could do the same with remove_child.


I forgot to mention the overridden add_child method won’t be called for children on a packed scene, so you may want to iterate through all the children on _ready and call your method there too.

I knew about the notifications but there isn’t one in there for having a child added (that I could see anyway). I suppose overriding add_child could work, although I intend for this to be tied to an editor tool and I don’t know if add_child is called upon adding a node in the editor. I’ll have to try it and see. I do think a more elegant solution should be added/considered, though.

Edit: I tested it and it does in fact work in-editor as I wanted. So I guess I’ll mark this as the correct answer. Thank you! :smiley:

bojjenclon | 2016-03-05 22:20