0 votes

extends Node2D

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

func onButtonpressed():
--->tex.instance().position
--->position = get
globalmouseposition()

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.

Godot version 3.2.1
in Engine by (69 points)
edited by

1 Answer

+1 vote
Best answer

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()

by (2,684 points)
edited by

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 (tes.gd)'. 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?

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.