How to use a string as a part of a variable name

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

I am working with programmatic node creation from a scene resource. I would like to spawn resources in the loop and change the spawned nodes position. What ends up happening is the same instance keeps getting re-added and the position of the resource is changed.

Is there a way to programmatically add a resource with a variable name that is determined via code. In php this would be done with curly brackets. $some_variable_{$some_string} so long as this results in a valid variable name $some_string could be anything. Is there something similar in gdscript?

Though your question has already been answered just wanted to note that there are functions var2str() and str2var() also to concatenate string values you can use the + sign or %s to insert or reverence a value e.g.

var foo = “bar”

var name = “soap %s” % foo
soap bar

var name = “foo” + var2str(foo)

Wakatta | 2021-01-09 00:53

1 Like
:bust_in_silhouette: Reply From: abelgutierrez99

I’m not sure of what are you trying to do, but you can add an attribute to the variable with the string. I mean, create a new class and add a variable to store that string. Then you can add an if statement to check that string.

Not quite what I am asking, Think of it in these terms. I am using a for loop to instance 10 scenes programmatically and I want them named foo_1 foo_2 … foo_10.

frob | 2021-01-02 04:48

I don’t know how to do that, but I would create a node, called foos for example, and then add foo_1,…,foo_10 as children. Then you can get access to them using built-in functions. Advice: use the same indexation as Godot foo_0,…, foo_9.

abelgutierrez99 | 2021-01-02 11:03

I ended up using the node’s name in the tree for what I was attempting to do. The issue was that I wanted to create an unknown number of things and so I couldn’t name the variables foo_1 through foo_n, but I can name the nodes and use add_child(foo, true) to set the name in the tree then use get_node to get a named node in the tree.

frob | 2021-01-08 18:02

:bust_in_silhouette: Reply From: frob

As far as I can tell this feature isn’t a part of GDScript, but as it turns out it isn’t really necessary either. This is because if we need to access a value later we can add it as a child to the node tree and access it later using get_node. This is pretty simple in practice: = bar
add_child(foo, true)```


```foo = get_child("bar")```