Is there a way to get any offspring that belongs in a certain group directly?

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

You can get all members of a group:

get_tree().get_nodes_in_group("group")

You can get all children:

get_children()

Is there a way to simply get specifically children that are in that group?
Is the only solution to get all children and then filter by their group?

:bust_in_silhouette: Reply From: jgodfrey

I don’t think there any single, built-in way to do that. I’d probably get the nodes in the group of interest and then get their children. So, something like this:

func _ready():
	for node in get_tree().get_nodes_in_group("the_group"):
		print(node.name)
		for child in node.get_children():
			print("   " + child.name)
:bust_in_silhouette: Reply From: Bernard Cloutier

Is the only solution to get all children and then filter by their group?

Yeah, or the other way around:

var children_in_group = []
for node in get_tree().get_nodes_in_group("the_group"):
    if is_a_parent_of(node):
        children_in_group.add(node)

Don’t know if this will be useful, but I found this thread first when I looked for a find_child_in_group function, here are the two I created if somebody has use for them

class_name Tools


static func find_child_in_group(parent: Node, group: String, recursive: bool = false):
	var output: Node = null
	for child in parent.get_children() :
		if child.is_in_group(group) :
			return child
	if recursive :
		for child in parent.get_children() :
			output = find_child_in_group(child, group, recursive)
			if output != null :
				return output
	return output
	
static func find_children_in_group(parent: Node, group: String, recursive: bool = false):
	var output: Array[Node] = []
	for child in parent.get_children() :
		if child.is_in_group(group) :
			output.append(child)
	if recursive :
		for child in parent.get_children() :
			var recursive_output =  find_children_in_group(child, group, recursive)
			for recursive_child in recursive_output :
				output.append(recursive_child)
	return output