+1 vote

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?

Godot version 3.2
in Engine by (42 points)

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)
foobar

2 Answers

+1 vote
Best answer

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:

var foo = node foo.name = bar add_child(foo, true)

...

foo = get_child("bar")

by (42 points)
0 votes

Hello,
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.

by (225 points)

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 foo1 foo2 ... foo_10.

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.

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.