The method instance()

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

So,we have this part of code:

var player=load(“res://MovingIcon.tscn”)
func _ready():
var inst=player.instance()
add_child(inst)
pass

I can understand the part of : ( player=load(“res://MovingIcon.tscn”) ) and the part of
( var inst=player.instance() ), OR we can say also:

var player=load(“res://MovingIcon.tscn”)
func _ready():
add_child(player.instance())
pass

But, what excactly does the instance() method?

Thank you.

:bust_in_silhouette: Reply From: Elis

If I’m not wrong, it creates a new object from the “template” loaded. Its equivalent is .new(), in exemple var alpha = Line2D.new(). Line2D is the template, and you create a new object from that.

Hmmm…The new object is not created with the add_child?

Nick888 | 2019-05-14 15:05

Definitely not, add_child() just renders it on screen. You can try to make an object, add_child() it on the screen, modify it in some way, then call the function remove_child() and add_child() again. You will see that it’s the same object, same reference, and the modifications are still here.
Even if the object isn’t a child of the scene, it exists in the memory.
That’s why you can change its name (or other properties) before adding it to the scene, but not before instancing it.

Elis | 2019-05-14 15:10

Oh i see…Now its clear!Thank you very much!

Nick888 | 2019-05-14 15:12