Code that works perfectly fine in one Scene doesn't work in another (preload and get_tree().current_scene)

Godot Version

4.1.1

Question

I’m going to post the code beneath (only the ones with the problem in it). I copy pastet the code lines from one script into the other and in the first they work. So I thought maybe its something with the other script being attached to the main scene? But I couldn’t find any information about that.

extends Control

var ed_name: Node

var speic: Node

var thema: PackedScene

var einbett_scene: PackedScene

var diese_scene: PackedScene

func _ready():
	
	thema = preload("res://Szenen/Thema.tscn") # thema is still null
# I checked the path for the scene multiple times
	
func _one(): # triggered by a button
	var scene_instance = thema.instantiate()
	scene_instance.set("num", 1)
	scene_instance.set("ziel_scene", einbett_scene)
	scene_instance.set("diese_scene", scene_instance)
	get_tree().current_scene.queue_free() 
# I get the error "queue_free() can't be used on a null value"
	get_tree().root.add_child(scene_instance)

Are both of the scripts active (being used) ?
And are they connected to the same button?

is this script an autoload?

No, the first script (where I dont get an error and which I will post beneath that anwser) is atteched to my main scene and home menu. I use the same get_tree().current_scene.queue_free() etc to get to the scene where the problems are happening. The code I posted at first is atteched to the screne I switch to.

And functions and the buttons are in different scripts/scenes.

Code in main scene:

extends Control

var neue_Scene

# Called when the node enters the scene tree for the first time.
func _ready():
	neue_Scene = preload("res://Szenen/Einbetten.tscn")

func _on_fra_pressed():
	var scene_instance = neue_Scene.instantiate()
	scene_instance.set("einbett_scene", scene_instance)
	get_tree().current_scene.queue_free()
	get_tree().root.add_child(scene_instance)
1 Like

No its attached to a scene. I open this scene in the main scene through basically the same code that doesnt work in the second scene.

Is it possible for you to sent a minimal Reproducible project if it’s not a barden to you?
Kinda having hard time visualizing it.

My guess is you are calling
get_tree().current_scene.queue_free() multiple times somehow.
You could do a null check before the queue free

if get_tree().current_scene != null :
   get_tree().current_scene.queue_free()
   # other codes that depends on current scene 

But yeah there probably is a better solution