Variable as a part of a name

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

I have five Sprites. The names are like this: Sprite1, Sprite2, … . And I have a variable. And I want to hide the Sprite which name end on the number of the variable. I think about somerhing like this:

var number = 4

func _ready():
   $Sprite+number.hide
:bust_in_silhouette: Reply From: kickinespresso

I think you can do this, but not with $ reference like that in GDScript. As /u/brainbug posted here: https://forum.godotengine.org/43578/how-to-get-a-variable-from-a-child-node you can get the child dynamically using get_node

For example, if you have:

- MyNode (Parent Node)
-- MySprite (Child Node)
--- MyOtherNode (GrandChild Node)  
-- MySprite2 (Other Child Node 2)
-- MySprite3 (Other Child Node 3)

You can use the $ reference the Child Node MySprite with $MySprite or the Other Child Node with $MySprite2.

or you could use the get_node function to get the child node. The pathing is relative so you could do it like this:

var mySprite = get_node("MySprite") # to get the Child Node
var mySprite2 = get_node("MySprite2") # to get the Other Child Node
var myGrandChild = get_node("MySprite/MyOtherNode") # to get the Grand Child Node

Now that you can do that, you can use string concatenation or interpolation to get the one you want:

var mySprite2 = get_node("MySprite" + "2") # to get the Child Node 2
var mySprite3 = get_node("MySprite" + "3") # to get the Other Child Node 3

or 

var mySprite2 = get_node("MySprite{number}".format({"number":"2")) # to get the Child Node 2

String Reference: GDScript format strings — Godot Engine (3.1) documentation in English

:bust_in_silhouette: Reply From: jgodfrey

You’re close, but you need to “assemble” the name and retrieve the node a little differently. Try something like this:

var spriteNum = 2	
var sp = get_node("Sprite" + str(spriteNum))
sp.visible = false