Problem changing scene

Godot Version

4.3

Question

i have 2 functions that are supposed to store and retrieve saved scene.

func save_progress():
	var file = FileAccess.open(save_path,FileAccess.WRITE)
	file.store_var(scene)
	file.store_var(collected)
	file.store_var(items)
	
func load_progress():
	if !FileAccess.file_exists(save_path):
		print("no data saved")
		scene = "room1"
	var file = FileAccess.open(save_path,FileAccess.READ)
	scene = file.get_var()
	print("load scene ",scene)
	get_tree().change_scene_to_packed(scene)

and

func _on_continue_pressed() -> void:
	Global.load_progress()

get_tree().change_scene_to_packed(scene) apparently works fine and returns 31, but it doesn’t change anything! instead it gives mistake
E 0:00:01:0701 global.gd:148 @ load_progress(): Can't change to a null scene. Use unload_current_scene() if you wish to unload it.

try to pass true to file.get_var() because scene is an object so you probably should decode it as object.

if this not solves the issue, could you show the output of the following line to provide more information about the issue?

hello! it doesn’t solve it.
the output is

load scene <EncodedObjectAsID#-9223372004961286840>

print(get_tree().change_scene_to_packed(scene)) prints 31

31 is error code, it means Invalid Parameter

Oh, the scene variable stores some string, not scene. Then passing true wouldn’t help, my bad.
But you can’t pass String to change_scene_to_packed anyway.

Are you trying to save a scene in a specific state? If not, you can do something like storing it’s name and then identifying the scene variable by it’s name:

enum scenes {ROOM_1, ROOM_2, ANOTHER_ROOM}
const room1 = preload("res://path/to/room1.tscn")
const room2 = preload("res://path/to/room2.tscn")
const anotherRoom = preload("res://path/to/anotherRoom.tscn")

#storing
file.store_var(scenes.ROOM_1)

#loading
scene = file.get_var()
match scene:
    scenes.ROOM_1:
        get_tree().change_scene_to_packed(room1)
    scenes.ROOM_2:
        get_tree().change_scene_to_packed(room2)
    scenes.ANOTHER_ROOM:
        get_tree().change_scene_to_packed(anotherRoom)

Saving scene’s state is more complex and I don’t know much about it, may be there is solution out of the box, but at least you can write your own seriliazing and deserealising functions, so you could store and read strings instead of objects.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.