How to Save a scene at run time ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By subhajitroy86
:warning: Old Version Published before Godot 3 was released.

Hi All,

I am working on procedural generated levels. So after having populated a scene at run, I would like to save it too at run time, so as to open that scene just like any other scene offline.

How do I save a scene at run time ?


:bust_in_silhouette: Reply From: neikeq

You can use method PackedScene.pack(node) to pack a node and its children into a PackedScene, and then save it with ResourceSaver:

var packed_scene =
packed_scene.pack(get_tree().get_current_scene())"res://my_scene.tscn", packed_scene)

You can then load the packed scene back and instance it as explained in the docs:

# Load the PackedScene resource
var packed_scene = load("res://my_scene.tscn")
# Instance the scene
var my_scene = packed_scene.instance()

Notice you must specify the format in the path extension. In my case I am saving my scene as .tscn. To get a list of all the valid extensions for a resource (PackedScene in this case) use:

# Returns: scn, res, xml, xscn, tscn


As mentioned by @subhajitroy86 in the comments, you must make sure to set the owner of the child nodes (otherwise the children won’t be saved):


That works. Except that when it is done for nodes added dynamically, we should make sure we set the owner of the child node, else the child nodes will not get saved.
This link can be of use for set_owner usage
Reddit - Dive into anything

subhajitroy86 | 2016-03-07 17:42

You’re right. I’ll include that in the answer.

neikeq | 2016-03-07 18:48

This link is the result of me finding this question. My gift to you for the questions and answers.

PlanetKiller | 2016-03-15 17:01

What’s the best approach to saving the path to the scene?

GhostWalker562 | 2019-06-22 00:13

where do we place that load packed scene code ?
i assume its on the

func _ready():

is this correct ?

ruruarchy | 2019-07-12 14:52

func add_owned_child(node: Node) -> void:

smashbrosonic | 2020-01-07 14:55

Sorry, but node variables are not saved. I tried to use it but nothing worked. The positions of the objects have been preserved, but not the rest.

roma | 2023-01-14 19:06