(Godot) Button to return to the last scene

Asked

Viewed 24 times

2

Good morning guys, I’m having a question at Godot to get back to the last scene. Should work as the "Continue" button after pausing the game.

I have a menu of options that is accessed when the user clicks pause. Now I need that by clicking a specific button on that menu, it goes back to the last scene that was.

/The game works as an interactive book, so there is no need to store a character’s data, for example. Just go back to the last scene/page./

I’m using this code here and it hasn’t worked:

extends Button

var saved = null

func save_current_scene():
    saved = get_tree().get_current_scene()

func reload_last_saved():
    get_tree().set_current_scene(saved)
    
func _on_Button_Pressed():
    get_tree().change_scene(saved)

I have tried to find other ways on the internet to do it, but they always use a Node and not a button. I tried to do it manually by changing these codes but I was still unsuccessful. I wish someone would let me know what I’m doing wrong.

Thank you in advance,

1 answer

2

From the looks of it, your menu is in a separate scene. In this case, you need to use a Singleton to store the current scene, before entering the menu scene. This way, you would have a reference to return to.

Something like that:

extends Control

onready var current_scene: Node = get_tree().get_current_scene()

func _process(_delta: float) -> void:
    if current_scene != get_tree().get_current_scene():
        current_scene = get_tree().get_current_scene()

In this example I gave, you still need to ensure that the menu scene itself is not included in the "current_scene". This can be avoided in many ways, a relatively simple way that I suggest is to check if the name of the scene is equal/includes some value:

var _current_scene = get_tree().get_current_scene()
if current_scene != _current_scene and _current_scene.get_name() != "menu":
    current_scene = _current_scene

Done this, on your button you can do something like this (assuming the name of your Singleton be "Globals"):

extends Button

func _on_Button_Pressed():
    get_tree().change_scene_to(Globals.current_scene)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.