+1 vote

A parent generates many mobs as children. The mobs want to get information about their surroundings from the parent.

Using get_parent() for this is bad practice, so instead, I've been using this elaborate combination of signals and callbacks:

Parent code:

    var child = Child.instantiate()
    child.connect("query_parent", _on_child_query_parent)
    add_child(child)

func _on_child_query_parent(sender, question):
    var answer = calculate(question)
    sender.callback(answer)

Child code:

    if wants_to_ask_question:
        emit_signal("query_parent", self, question)

func callback(answer):
    use_received_info(answer)

Are there any better or simpler ways for a child to get information from its parent?

Godot version v4.0.beta10.official [d0398f62f]
in Engine by (13 points)
edited by

1 Answer

+1 vote

You could use dependency injection to inject a reference of the parent into the child node when instantiating it:

var child = Child.instantiate()
child.init(self)
add_child(child)

func on_child_query_parent(sender, question):
    var answer = calculate(question)
    sender.callback(answer)

And request the info as such:

func init(parent):
    Parent = parent

if wants_to_ask_question:
    Parent.on_child_query_parent(self, question)

func callback(answer):
    use_received_info(answer)

I'm not sure if this is actually any better than using signals, but it's an alternative. :)

by (16 points)
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.