Luis Carli

I'm a designer and creative coder making video-games [more]

Saving Runtime Changes Back into the Scene

Coding procedural node manipulations in the _ready callback, executing that code when running the scene, and then saving those modifications back into the scene is an nice quick alternative to creating custom tools and plugins in Godot.

Typically, it’s faster to create, position, and manipulate nodes in the Godot editor. However, there are times when mathematical logic and precision are required, and coding the creation and manipulation of nodes becomes more desirable. For example, when arranging several boxes in a grid with fixed spacing.

A challenge arises when I want to have a procedurally generated setup and then add and modify elements on top of that through the editor UI. The goal is to use each method where it excels, transitioning back and forth between them.

In Godot, there are two main ways to run code in the editor and modify the current scene. You can use the @tool keyword, or create plugins. Sander Vanhove provided a comprehensive talk about editor plugins and tools at GodotCon 2023.

However, these solutions can be too complex for certain needs. The @tool keyword in nodes can create many edge cases, and plugins require a significant setup. Neither is ideal for quick iterations and frequent code changes. A more straightforward solution is preferable.

One approach I frequently use is saving runtime changes back into the editor. When the scene runs, code in the _ready function creates new nodes and modifies existing ones. These modifications can then be saved back into the scene and further developed in the editor.

Here’s an example of how to save the scene:

func _input(event: InputEvent):
	if event.is_action_pressed("save_scene"):
		var scene = get_tree().current_scene
		var file_path = scene.scene_file_path
		
		var packed = PackedScene.new()
		packed.pack(scene)
		ResourceSaver.save(file_path, packed)

It’s important to note that only nodes with their owner property set to the current scene will be saved. This happens automatically for nodes created in the editor, but it needs to be done manually for nodes created in code.

Published 2023.11.22

Get New Game Updates via Email!
No spam, no intermediaries, just the good stuff delivered straight to you.