Modify a node after instancing it

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

So I have a list of “items” that I want to load into some label nodes. The label is instanced when you run a function. I want to be able to load in values into these instanced labels using set_text but I’m not sure how to reference it.

An example:

var info_node = infowhatever.instance()
add_child(info_node)

get_node(info_node).set_text(info_one_var)

How would I go about doing this or is there a more fundamental way of achieving this? Thanks.

:bust_in_silhouette: Reply From: Diet Estus

You can just use the info_node reference that you set when you instanced the node.

info_node.text = "whatever text you want"

If you have multiple nodes being instanced, taking turns being the reference of the variable info_node, and you are “losing” the reference to them, consider giving them unique names when you instance them. Then you can reference them later using the names. For example:

var counter = 1
...
var info_node = InfoNode.instance()
info_node.name = "my_node_" + String(counter)
counter += 1

Now I can reference the node and set its text like this:

var node_to_change = get_node("/root/.../my_node_1")
node_to_change.text = "whatever text you want"

Alternatively, when you add the Label nodes to the scene, you can also add them into an array, or even as children of a simple Node which you are using just as a container for them. Then you can reference them using their position index.

Here’s an example using an array:

 var label_array = []
...
# the Label node is added to the array during your creation code
label_array.append(InfoLabel.instance()]
...
# to reference it later using an index (assuming it's 0)
var node_to_change = label_array[0]
node_to_change.text = "whatever text you want"

And here’s an example using a basic Node as a container (assume its name is “LabelContainer”)

var label_container = get_node("/root/.../LabelContainer")
...
# the Label node is added as child during your creation code
label_container.add_child(InfoLabel.instance()]
...
# to reference it later using an index (assuming it's 0)
var node_to_change = label_container.get_children()[0]
node_to_change.text = "whatever text you want"

Thanks that was extremely helpful. And of course, I can just set the property without using a function… Thanks again.

jobax | 2018-04-13 14:58

I seem to have another problem with my particular nodes though. Basically the node I’m instancing is a HBoxContainer with labels inside it. How do I reference the node that would be a child of the node that I’m instancing? Thanks.

jobax | 2018-04-14 03:18

Hmm nevermind. info_node.get_child(0) works!

jobax | 2018-04-14 03:20

Yes, or you can do something like info_node.get_node("Label1").

Diet Estus | 2018-04-14 03:30

Even better, more readable. Thanks!

jobax | 2018-04-14 03:32