0 votes

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?

in Engine by (76 points)

1 Answer

+2 votes
Best answer

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://BaseAlien.gd"
#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
by (140 points)
selected by

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.

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.