Can you construct a variable name with a string?

Godot Version

4.3

Question

So I have a ton of text boxes in my code. To call them, I reference a variable that contains “$node_path”. Which works perfectly fine. I called the variables I1, I2, I3, etc.

I am trying to create a loop that calls the same function in every node. Instead of calling every variable separately, can I create a new variable that combines “I” and the step of the loop and call a function in it, as if I was calling the node? If so, how?

I’ve tried

for i in range(1, 70):
var Item = str(“I”, i)
Item.function()
But it doesn’t work

Godot provide many ways to do that.

  1. Set specific group to all these nodes and use get_tree().call_group(...)
    SceneTree — Godot Engine (stable) documentation in English

  2. Hold all this variables in array for example and call array_name.all(func(i): i.function(); return true)
    Or iterate over this array like

for i in array:
  i.function()
  1. This is what you want literally, but not best way IMO
for i in range(1, 70):
  var item = str("I", i)
  self[item].function()

beware range (1, 70) will iterate from 1 to 69

I would have believed that the Nodes are all named in a specific incrementing way and all children have the same parent node.

for i in range(1, 70):
    var element = get_node("PATH/TO/node" + str(i))
    if not element: return
    if element.has_method("someFunction"):
        element.someFunction()

also added some crash safety

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.