Function for all members of a group?

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

I’ve just discovered groups and understand basically how they work, but I’m wondering if there’s a better way to call an identical function for several members of a group. Let’s say that I have 10 types of alien in my scene and they’re all in a group. When I hit the spacebar, I want them all to respond in the same way. As far as I can tell, the way to do this is something like

get_tree().call_group("aliens", "spacebar")

And then in EACH of the alien scripts, have a ‘spacebar’ function that does whatever. This is fine if they all reacted differently, but if the function is the same in each script, that seems like a lot of extra work.

I’m wondering if there’s a way to have a sort of ‘Group script’? Or would I just do this completely different, e.g when the spacebar is hit, cycle through the members in the script that detects the input and do the processing there?

:bust_in_silhouette: Reply From: TheThirdPerson

If the function is always the same, why not have all of the aliens inherit from some sort of “BaseAlien” scene that already has this function in the script? That way you wouldn’t have to re-define it in each of your different alien types. You might have something like:

extends Node2D
func _ready():

func spacebar():
  #do some generalized spacebar task

extends "res://"
#Now we will already be part of the aliens group and have a spacebar function

#We can also still override the spacebar function to add specific functionality for this type of alien, and then call the parent function for the generalized functionality.
func spacebar():
    #Do something specific to this alien if applicable
    return .spacebar() #Call the parent function

Thanks, I hadn’t thought of inheritance, that does fit the bill. I temporarily skipped around it by simply having the function in the main script and looping through the aliens in the group but this looks like a better solution.

Farflame | 2019-04-24 19:39