Sending Signals to Parent and Child Objects

martymarty Posts: 112Member
edited March 25 in Programming

Is it possible to send a signal based on the scene hierarchy?

That is to say, instead of coding listeners and receivers using direct references, could I instead send a signal to a Node's parent Node? Or send a message to all of the children of a Node? Stuff like that.

Thanks!

Answers

  • kryzmakkryzmak Posts: 57Member

    Short answer: No (At least I am pretty sure)

    Long answer: You could set booleans in respective nodes and listen to changed states via _process(). But in this case you would have to set the boolean for every individual node. That means more code instead of using signals. Also you would be very dependent on a fixed node structure (e.g. by names/order). If you change parent/child relation you would have to change the code.

  • martymarty Posts: 112Member
    Answer ✓

    Yeah, I'm thinking this approach doesn't honor the spirit of signals, which I gather prefer the explicit a-priori linking of objects that will talk with each other.

  • bitwesbitwes Posts: 60Member
    Answer ✓

    I've used call_group to accomplish a similar thing. All the objects have to belong to the group you specify, but you can easily call a method on all the objects in the tree that are that group.

    Here's how I update the speed on all the "traffic cars" in my game.
    get_tree().call_group_flags(0, _g.TRAFFIC_GROUP, 'set_speed', new_speed)

    I don't know what the 0 does, but in all the places where I'm using it, I pass 0. You can use call_group instead of call_group_flags I think, then you don't have to pass 0. Everything after the 3rd parameter gets passed to the method that is called. So you can actually pass any number of parameters to call_group_flags

    Disclaimer: I'm actually using call_group and passing 3 things but I think that is a bug in my code that is leftover from porting to 3.0. I have to fix it but didn't want to hold up this response while I re-test my entire game.

  • martymarty Posts: 112Member
    edited April 10

    Thanks, Bitwes. That looks like a very useful technique!

    At this point though, I'm inclined to avoid techniques that use Godot-only constructs like Groups. After 14 years using Unity3D and now migrating away (hopefully to Godot) I'm pretty gun-shy about lock-in. ;-)

Sign In or Register to comment.