This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
+8 votes

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?

in Engine by (30 points)

1 Answer

+7 votes
Best answer

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.

by (488 points)
edited by

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 addchild could work, although I intend for this to be tied to an editor tool and I don't know if addchild 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! :D

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.