How to turn a node into a PackedScene via GDScript?

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

I wanted to turn a child node into a PackedScene (in runtime) just to make some edits and instance copies of it.

:bust_in_silhouette: Reply From: Adam_S
func save_as_scene():
    var file_path = "res://your_scene.tscn"
    var scene = PackedScene.new()
    scene.pack(get_node("your_node"))
    ResourceSaver.save(file_path,scene)

Make sure you set the owner for each child of your node, otherwise they won’t be saved.

So, if I don’t want to save on disk by using ResourceSaver.save(), will I get a PackedScene with scene.pack()?

JulioYagami | 2019-08-18 11:50

Yes, tested it.

Adam_S | 2019-08-18 12:26

If you are using tool scripts, i suggest using these flags for the resource saver:

ResourceSaver.save( path, resource, ResourceSaver.FLAG_CHANGE_PATH|ResourceSaver.FLAG_REPLACE_SUBRESOURCE_PATHS)

This will trigger a refresh of the editor.

frankiezafe | 2021-07-06 10:27