How to make variables for scripts running in the editor not save to the scene file in Godot

Godot Version

Godot4.4

Question

I designed a script for the Sprite2d class that can apply multiple shaders at the same time, with an internal variable first_sub_viewport of the SubViewport type that references the first dynamically generated sub-viewport node. In order to show the effect in real time, this is a tool script and runs in the editor.
But there’s a problem with this variable being automatically saved when Godot is turned off. Then when you open it, you will get an error like "ERROR: Path to node is invalid: ‘EffectShow/ShadersSprite2D/@SubViewport@21740’.
”。

Now I want this variable not to be automatically saved to the scene file, so that it may not be loaded with this editor error. Although it does not affect the code running.
Code link:ShadersSprite2D/shaders_sprite_2d.gd at main · youer0219/ShadersSprite2D · GitHub


屏幕截图 2025-03-07 202326

You can use the NOTIFICATION_EDITOR_PRE_SAVE and NOTIFICATION_EDITOR_POST_SAVE to modify the scene before and after saving it.

Remove the ViewportTexture before and apply it back after

Example:

@tool
extends Node


var texture = preload("res://icon.svg")


func _ready() -> void:
	$Sprite2D.texture = texture
	
	
func _notification(what: int) -> void:
	match what:
		NOTIFICATION_EDITOR_PRE_SAVE:
			# remove the texture from the sprite
			$Sprite2D.texture = null
		NOTIFICATION_EDITOR_POST_SAVE:
			# put back the texture
			$Sprite2D.texture = texture

1 Like

Correct! And my previous question was based on a misunderstanding. I mistakenly thought I had incorrectly saved a node, but it turned out the issue was with saving the viewport-texture. I had misdiagnosed the problem! Thank you so much for your answer! This is absolutely brilliant!

Final Fix Code: