How to save node like scene via code

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

Basically i need to save a node like a scene,but i cant find anything for that. Is it possible to do that at least?

2 Likes
:bust_in_silhouette: Reply From: GlitchedCode

Yes there is a way to save a node as a scene at runtime in Godot 4 using GDScript.

var node_to_save = $Node2D

var scene = PackedScene.new()

scene.pack(node_to_save)

ResourceSaver.save(scene, "res://MyScene.tscn")

The first line of code creates a variable called node_to_save and assigns it the value of the Node2D node in the scene tree I want to save. The $Node2D notation is a shorthand way of accessing a node in the scene tree by its node path. In this case, it assumes that there is a Node2D node with that name in the same scene as the script.

The next line of code creates a new PackedScene instance and assigns it to a variable called scene. This is an empty scene that we will use to pack our node_to_save into.

Next block of code “packs” the node_to_save into the scene. This means that the scene now contains a copy of the node_to_save, and we can save the scene as a separate file if we want.

Our final line of code saves the scene as a file named “MyScene.tscn” in the “res://” directory. The ResourceSaver class is used to save the scene as a .tscn file, which is the format used by Godot Engine for scenes.

saved nodes are 1kb size and cannot be used.

vania23 | 2023-03-22 12:22

nvm im just stupid

vania23 | 2023-03-22 12:31

7 Likes