Is it possible to change the name of the $Node strings in the code?

Godot Version 4.3

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

You could try changing your logic a bit and use :

find_child() - by name, the custom logic instead of match/if else.

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.

This code helped me
get_node(“node_name” + “something else”)
Suitable for “for i in x”

for i in 100:

num = get_node(“box/x” + str(i))

1 Like

Yeah, that is what I was getting at with a “little” custom logic. :slight_smile: 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.

1 Like

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
3 Likes

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
1 Like

Just FYI I didn’t mean you couldn’t change the name property, I meant you cannot change the symbol name at runtime. The code is already compiled.

I was a bit confused with the OP originally and the question.

(They wrote $Node + “2”)

1 Like