Best practice for child to request info from parent?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By marcin42

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?

:bust_in_silhouette: Reply From: ZeroComfort

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. :slight_smile: