Godot 4.2 - Switch Scenes, Handle Scenes and Quit Game by GDScript

Setsuna
239 words

In this article, Setsuna will walk you through a handy GDScript class that simplifies the process of switching scenes, reloading the current scene, and quitting the game.

SceneManager class

To streamline scene management in a Godot project, a custom GDScript class named SceneManager will be created. This class will utilize a dictionary to store the paths to different scenes, making it easier to reference them with friendly aliases.

Setsuna is using Godot version 4.2-dev, but the concept is the same for various versions.

Here is he code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
extends Node
class_name SceneManager

@export var Scenes : Dictionary = {
"main": "res://scene/main_screen_fisrt.tscn",
"somescene": "res://path_to_file"
}

var m_CurrentSceneAlias : String = ""
var scene_to_switch_to : String

func AddScene(sceneAlias : String, scenePath : String) -> void:
Scenes[sceneAlias] = scenePath

func RemoveScene(sceneAlias : String) -> void:
Scenes.erase(sceneAlias)

func SwitchScene(sceneAlias : String) -> void:
get_tree().change_scene_to_file(Scenes[sceneAlias])

func RestartScene() -> void:
get_tree().reload_current_scene()

func QuitGame() -> void:
get_tree().quit()

How to use

Initialization: First, configure the Autoload feature in project settings. This step ensures that the SceneManager class is accessible throughout out whole project.

In the example provided by Setsuna, an instance with the name “SM” of the SceneManager.gd script is created.

Just call the function aloud, or with the nickname when the function needs one.

For example:

1
2
3
4
5
6
7
8
func _on_quit_pressed():
SM.QuitGame()

func _on_main_menu_pressed():
SM.SwitchScene("main")

func _on_restart_pressed():
SM.RestartScene()

That’s it. Really simple.

May you have a smoother game development,
and happy game-making with Godot 4.2!
Setsuna
12/10/23 Midnight