Naming instanced scenes

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

I’ve been trying to name instanced scenes because I need to handle them separately in the future, but it seems like my set_name() command is ignored completely. I made a short code to test it out, printing the instanced scene before and after set_name() and add_child().

extends Node
var random_scene = preload("res://teste.tscn")

func _ready():
	var random_instance = random_scene.instance()
	print(random_instance)
	random_instance.set_name("random_name")
	print(random_instance)
	add_child(random_instance)
	print(random_instance)

All that I get in the output is:
[Node2D:972]
[Node2D:972]
[Node2D:972]

What am I doing wrong here?

:bust_in_silhouette: Reply From: kidscancode

You’re trying to print the node reference. If you want the Node’s name, try print(random_instance.name) instead.

Also, note that you can set the name property directly rather than using set_name(): random_instance.name = "random_name"

Remember, sibling nodes must have unique names, so it’s not a good idea to rely on the node name, as it could be changed depending on where you add it in the tree.

I’ll be giving the instances unique names.
And how do I access the node using its name?
For example, if I want to change its position?

bwahaha | 2019-01-06 22:04

There are multiple ways. You can keep a reference to it, as with your variable above, you can use get_node().

kidscancode | 2019-01-06 22:20

Could you please give an example?

bwahaha | 2019-01-06 23:08

If you named the node “random_name”, then you can access it using get_node("random_name"). Set its position with get_node("random_name").position = <desired position>

If you haven’t yet, I highly recommend the Official Tutorial - it covers many of these topics.

kidscancode | 2019-01-06 23:39