is it possible to change the name of the $Node strings in the code?
like $Node + “2” = $Node2
or optimize this code below to not write
(elif Global.name == “x2”:num = $box/x2) 1000 times?
var num
func _num():
if Global.name == "x":
num = $box/x
elif Global.name == "x2":
num = $box/x2
elif Global.name == "x3":
num = $box/x3
I found a code that suits me
maybe it will be helpful to someone
func _num():
for i in 100:
if Global.name == "x" + str(i):
num = get_node("box/x" + str(i))
Think of the $ as const fields assigned at construction, they are immutable if I am thinking correctly.
It’s like trying to change a variable name at runtime, it’s just a reference pointer at that time, so changing the alias to that isn’t possible, the code is using an integer at that point, the variable name in script name is just coding sugar.
Yeah, that is what I was getting at with a “little” custom logic. Cool.
EDIT: Just for FYI, the find_node() will return null, if the node is not found as a child and not recursive. The get_node() will throw an error and return null if the node is not found, subtle differences in behavior for different use case.
Yeah get_node, or get_node_or_null is what you want, the dollar sign operator is a shorthand for the former, but it cannot use runtime formatted strings as you want.
You can also use % to format strings, this could be more helpful if your incrementing number is earlier in the node’s name.
for i in 100:
num = get_node("box/x%d" % i)
Another option is get_child if you do not know the name, often the case with runtime generated nodes.
for i in 100:
num = $box.get_child(i)
And a extra tip to format code on the forum use three ticks before you paste like so
```gd
# this is a code block
func _num() -> void:
return 4 # chosen by random dice roll
```
Will result in this:
# this is a code block
func _num() -> void:
return 4 # chosen by random dice roll
You can change the name of a $Node by assign it a new name.
E.g.
print($Button.name) # Prints $Button
$Button.name="Button2"
print($Button2.name) #Prints Button2
print($Button.name) # Error Invalid access becase you changed the name