Instancing by Code

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

I want to know how to instance a scene when a signal was detected

func _on_Point_score():
(instance_scene)

Thanks in advance!

:bust_in_silhouette: Reply From: BraindeadBZH

First you use preload to get a PackedScene with which you can instantiate your scene.

NOTE: a correction of this code is below  
onready var scene = preload("res://path/to/scene")    
    
    func _on_Point_score():
        return scene.instance()

ichster | 2019-08-28 17:59

Why do return the value?

You have to add your scene as a node with add_child.

BraindeadBZH | 2019-08-28 18:19

It returns with an object because you have to add that object to a node as child.
someNode.add_child(yourNewSceneInstance)

It is in the official documentation.

DavidPeterWorks | 2019-08-28 18:42

You’re correct, but why not do the add_child in the signal handler. Also due to the way signal are working, there is no way to store the return value, so your instance will actually never be used.

Edit: I just realized that none of the comments above where made by the original user, so I was kinda confused with the answers.

BraindeadBZH | 2019-08-28 20:35

I would add the child in the signal handler :). I just wanted to show in the quickest way possible how to instance a scene. This is the correction:

onready var scene = preload("res://path/to/scene")    

func _on_Point_score():
    self.add_child(scene.instance())

ichster | 2019-08-31 00:48