Obtaining a ButtonGroup reference in GDScript

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

I have several buttons that are part of a ButtonGroup. It wasn’t clear to me how to then access these buttons via the group from a script. My first intuition was to load the group resource via the resource path the editor provides. The group is local to my scene.

However, doing the following returns a ButtonGroup instance that is not the same as the one in which the buttons actually reside:

onready var btn_group = load("res://myscene.tscn::1")

This does return an instance of ButtonGroup, but it contains no buttons.

Instead, the only way I found to get hold of the correct group is by first accessing a button inside it, then accessing its group property:

onready var btn_group = $FirstButtonInGroup.group

That seems backwards. How do you access a button group without holding references to individual buttons? Isn’t that the point of a button group?

Related question: I can Name the button group in the editor. What purpose does that serve? I could find no way to actually utilize this name to e.g. obtain a reference to it.

mkx | 2023-04-02 17:10

Have you looked at the article on Groups in the documentation? Have you tried code like the following?

 var button_group = get_tree().get_nodes_in_group("ButtonGroup")

Ertain | 2023-04-02 20:17

Same issue: this returns an empty array []. It seems to also reference a different group instance. I am not sure what’s going on here. All I do is set the checkbox on each button and give the group a name. Are these different kinds of groups? And I can see it’s being embedded in the scene file.

mkx | 2023-04-03 05:58

:bust_in_silhouette: Reply From: Vadalken

I have the same issue and have found another solution that feels like a workaround.

@export var *variable_name*: ButtonGroup

Export a ButtonGroup variable and then use the inspector to load a saved button group.