Godot has built-in properties to pause the game and control what the player can do while the game is paused.
Pausing the game with get_tree().paused
To pause the game, you need to:
- Get the game's scene tree (it's the object that manages all the nodes in your game) by calling
get_tree(). - Change the
paused property of the scene tree to true.
get_tree().paused = true
To unpause the game, you set the scene tree's paused property to false.
get_tree().paused = false
By default, this pauses all nodes in your game, which will prevent the player from doing anything, including navigating a pause menu or unpausing the game.
To control which nodes pause and which continue running, you need to change the process mode property of the nodes you want to control.
Keeping nodes active while the game is paused
When you select a node, if you scroll to the bottom of the Inspector dock, you will see the property ProcessMode.
By default, it's set to Inherit, which means the node will inherit the pause behavior from its parent node. By default, the root of the scene tree is paused when the game is paused and that's why all nodes in the game are paused.
You can set a node's ProcessMode to Always instead to keep it and all its children running while the game is paused.
You can do this for the root node of a pause menu or a game over menu, for example, to keep it interactive while the game is paused.
Here's how to do it in code:
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS
Toggling pause with a key
You can toggle the game's pause state by checking if a key is pressed in the _input() function.
func _input(event: InputEvent) -> void:
if event.is_action_pressed("toggle_pause"):
get_tree().paused = not get_tree().paused
In this code, we:
- Check if the input action
"toggle_pause" is pressed. Doing this in the _input() function allows you to catch input events before the user interface and other nodes in the scene. - Toggle the game's pause state by setting the scene tree's
paused property to the opposite of its current value. If the game is paused, the paused property will be true, and writing not before it will set it to false, and vice versa.
NOTE:You'll need to register the input action "toggle_pause" in the project settings for this code to work. Go to ProjectProject Settings...Input Map to register an input action.