Create a scene from code.

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

How do a create a completly new scene from gdscript, there seems to be no Scene class.

:bust_in_silhouette: Reply From: MagnusS

A scene is just a node and it’s children saved to a file. That’s all.

You probably just want to create a node and then add some children to it. If you relly want to save a scene (I.e. because you’re working on an editor plugin) than this QA-post might help you.

Thanks, this definitely helps.

magicalogic | 2021-05-06 13:19

:bust_in_silhouette: Reply From: idbrii

See Nodes and scene instances for godot 4 or godot 3.6.

Here’s some examples copied from that page.

Building a new scene

var sprite2d

func _ready():
    var sprite2d = Sprite2D.new() # Create a new Sprite2D.
    add_child(sprite2d) # Add it as a child of this node.

func _done():
    sprite2d.queue_free()

Instantiating a new scene from the project

If you already built and saved a scene but it’s not already in the active scene, you can instantiate it.

var scene = preload("res://my_scene.tscn")
func _on_Area_body_entered():
    var instance = scene.instantiate()
    add_child(instance)

(This question has high pagerank, so I wanted to add answers that would have helped me when I started looking.)

idbrii | 2023-06-08 13:40