how to get the instance of a TSCN, to stay to the tip of a mouse cursor ?

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

extends Node2D

onready var tex = preload(“res://TSCN/Item.tscn”)

func _on_Button_pressed():
—>position = get_global_mouse_position()

i don’t know why but all the button disappear when i pressed the button.
i want to make it that the tscn follow and stay in the tip of the mouse when i clicked the button.

:bust_in_silhouette: Reply From: Lopy

When you use preload(“res://TSCN/Item.tscn”), you get a PackedScene. It is like a schematic to create the scene. Therefore, there is no single instance, but as many as you want.

When you call instance() on your PackedScene, it returns a Node, with potentially other ones attached to it. To display them, you have to put them into the main tree using add_child() on a Node present in the tree. Note that adding the top Node will by extension add it’s children “automatically”.

If you run code inside your onButtonpressed, it will only be run once per press. To make tex follow your cursor, you can run it inside a _process().

In short, you get :
onready var tex = preload("res://TSCN/Item.tscn").instance() //Not the PackedScene, but an instance of it
var follow := false

func _ready():
. add_child(tex) //Not the PackedScene, but an instance of it

func onButtonpressed():
. follow = true

func _process():
. if follow:
. . tex.position = getglobalmouseposition()

hai thank you for the reply sir, you code make sense, but when i apply it, it give an eror
" Invalid type in function ‘add_child’ in base ‘Node2D (’. The Object-derived class of argument 1 (PackedScene) is not a subclass of the expected argument class."
can you explain to me what’s is means?

szccornish | 2021-01-02 06:55