This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
+2 votes

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
in Engine by (378 points)

2 Answers

+2 votes
Best answer

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
by (22,704 points)
selected by
0 votes

I think you can do this, but not with $ reference like that in GDScript. As /u/brainbug posted here: https://godotengine.org/qa/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: https://docs.godotengine.org/en/3.1/getting_started/scripting/gdscript/gdscript_format_string.html

by (16 points)
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 Frequently asked questions and 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 [email protected] with your username.