I've been having a hard time trying to figure out how to save and load scene's state. I'm trying to move back and forth between scenes without having them reset to their initial state each time. Ideally, id like to load a scene as it was when the transition was triggered.

I've been working off of this simple function in my global script:

var currentScene 

func setScene(scene):
	currentScene.queue_free()
	var newScene = ResourceLoader.load(scene)
	currentScene = newScene.instance()
	get_tree().get_root().add_child(currentScene)

This just switches the scene, but I've been trying stuff like:

 var sceneState

func setScene(scene):
    sceneState = get_tree().get_current_scene()
    get_tree().get_root().remove_child(sceneState)
    var newScene = load(scene).instance()
    get_tree().get_root().add_child(newScene )
    get_tree().set_current_scene( newScene )


func load_scene():
    if sceneState != null:
        get_tree().get_current_scene().queue_free()
        get_tree().get_root().add_child(sceneState)
        sceneState = null

This one seems right, but it crashes with a null reference exception, pointing to scene scripts where I call get_node()

Any tips or help would be much appreciated. Thanks in advance

6 days later

There's no way, that I know of to save off a scene in its current state. You could remove it from the tree and hold onto a reference to it but it will continue to take up RAM. I think child nodes of the scene will stay in the object and processing will stop once the scene is removed from the tree, but I'm not sure.

Once you queue_free something, it's gone. The only way I know of to save and then reload the state of a scene would be to come up with some way to write your state to disk. You'd have to come up with a way to save all the information about your scene to a file and then reload it. This is possible but it can get hairy quickly.

Usually, instead of saving everything, you'll just save a few things. Like if the scene had a chest in it, you would save it was open or closed, which enemies were defeated. You wouldn't try to save the location of all the enemies and their current hitpoints etc.

20 days later

NOTE* this is an assumption I have not tried this myself... you have to store the variables or whatever is causing the crash in a "main" script file and dynamically do it all from there... key is anything that needs to be referenced needs to be kept in memory to avoid empty pointers....or possibly issue a wait to ensure what ever you are referencing is fully loaded before accessing it. I apologize if this answer is vague, as I have little experience with the engine....after writing this I realize this is an older post and you have probably moved on...but for posterity I will leave it in case anyone else may do a search...I do not have a direct answer but I feel I can push them in the right "logical" direction.

6 years later