Referencing dynamically generated nodes

Godot Version 4.2.2

Question

Hey all,
I’m a total beginner with Godot and learning how stuff works.
What I’m trying to do is create multiple buttons and then change their position.
For the first generated button I can use the $GroupForMain/Building.position

but the second one is $GroupForMain/@Button@2.position and so on.

How come its naming is changed to its type and is there a way to make them all the same or at least get the list of all the buttons under the $GroupForMain so I could loop through it to change positions?

var buildingButton: PackedScene = load(“res://building.tscn”)
func add_new_building():
var buildingInstance = buildingButton.instantiate()
$GroupForMain.add_child(buildingInstance)
func _ready():
add_new_building()
add_new_building()
add_new_building()
$GroupForMain/Building.position = Vector2(300, 300)
$GroupForMain/@Button@2.position = Vector2(400, 400)
$GroupForMain/@Button@3.position = Vector2(500, 500)

You can do like this:

var buildingButton: PackedScene = load(“res://building.tscn”)

func add_new_building(pos):
    var buildingInstance = buildingButton.instantiate()
    $GroupForMain.add_child(buildingInstance)
    buildingInstance.position = pos

func _ready():
    for i in range(2):
        add_new_building((Vector2(100, 100) * (i+1)) + Vector2(200, 200))

It is the short and best way :sweat_smile:, there are many ways but I recommend you to use this

1 Like

Thanks. That helped.
P.S
maybe you know if there is any way to get the list of items in the $GroupForMain that I could loop through each of its items?

1 Like

Yes, you can do like this:

for i in $GroupForMain.get_children():
    #whatever you can do