how to iterate variable names?

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

I apologize if this is the wrong category/question title
Currently I have a code for a simple rts that updates the overlay to show what units you can build at certain ‘buildings’ (planets in this case).
The way I set this up is I have a control with a grid container and 5 build buttons for units and the code I have is this:

$PlanetOverlay/BuildButtonsContainer/Build1.text = planet.buildableShips[1]
$PlanetOverlay/BuildButtonsContainer/Build2.text = planet.buildableShips[2]
$PlanetOverlay/BuildButtonsContainer/Build3.text = planet.buildableShips[3]
$PlanetOverlay/BuildButtonsContainer/Build4.text = planet.buildableShips[4]
$PlanetOverlay/BuildButtonsContainer/Build5.text = planet.buildableShips[5]

(buildableShips is a dictionary for the units buildable at each planet and BuildButtonsContainer is the grid container)

However, this seems rather clunky and could get hectic when I need 10-20 buttons.
Is there anyway to do this with a for loop? I know you can for the buildableShips dictionary, but I’m not sure how to do this for getting a child node.

:bust_in_silhouette: Reply From: x2f

One way to do it might be to make sure your controls Build1/2/3/… are the only children of BuildButtonsContainer, and then use $BuildButtonsContainer.get_children() to get an array [Build1,Build2,…]. Something like:

var builds = $PlanetOverlay/BuildButtonsContainer.get_children()
for i in range(len(builds)):
  builds[i].text = planet.buildableShips[i+1] 

Thanks a lot!
This is a lot simpler than what I had in mind and works like a charm!

Agentfox | 2019-04-28 16:16

:bust_in_silhouette: Reply From: brainbug

in a loop use `

$PlanetOverlay/BuildButtonsContainer.get_child(index)

`index is a integer
2.

use a Format String

var path := "PlanetOverlay/BuildButtonsContainer/Build%s"

in the loop

get_node(path % index).text = ...