+27 votes

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 ?

Regards
Subhajit

in Engine by (25 points)

1 Answer

+36 votes
Best answer

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 = PackedScene.new()
packed_scene.pack(get_tree().get_current_scene())
ResourceSaver.save("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()
add_child(my_scene)

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
ResourceSaver.get_recognized_extensions(packed_scene)

EDIT:

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

add_child(new_child)
new_child.set_owner(self)
by (488 points)
edited by

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
https://www.reddit.com/r/godot/comments/354qg3/how_can_i_add_nodes_with_script_that_are/

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

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

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

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

func _ready():

is this correct ?

func add_owned_child(node: Node) -> void:
    add_child(node)
    node.set_owner(self)
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.