Make Games with Godot 4 and AI · Lesson 7 of 11

Godot 4 UI: Title Screen, Game Over & Autoload (Lesson 7)

Start from a title screen, clear the stage by collecting every coin, get a game over after 3 enemy hits, then play again. You'll build the UI with Control nodes, anchors, and containers, and use an Autoload to remember the score across screens.

In Lesson 6, collecting coins started raising the score, and touching an enemy sent you back to the start. But nothing happens when you collect every coin, and no matter how many times you get hit, the game never ends. In this lesson, we'll build the UI (user interface) and complete one full "loop" of the game: title screen → game → clear or game over screen → play again.

Finished project for Lesson 7: project-lesson07.zip (16 KB)

The title screen. In the middle of a light blue background, the text "Hop Hop Coins," the character's picture, the text "Collect all the coins!", and a "Start" button are stacked vertically
The title screen we'll make in this lesson. Press the button and the game starts

How Control nodes differ from Node2D

The Sprite2D and CharacterBody2D nodes we've used so far belong to the Node2D family. When you build on-screen UI like buttons, text, and panels, you use the Control family instead (the ones with green icons when you add a node). The Label we used for the score in Lesson 6 is a Control too.

Node2D familyControl family
Main useThings inside the game world (characters, enemies, floors)On-screen UI (text, buttons, menus)
How position is setPosition (coordinates)Anchors (where on the screen it sticks) and size
How things are arrangedYou set the coordinates yourselfPut them in a container and they line up automatically
Mouse and keyboardYou write the code yourselfButton clicks, focus, and so on work out of the box
ExamplesSprite2D, Area2D, Camera2DLabel, Button, ColorRect, VBoxContainer

The most important idea in UI is anchors. They decide which part of the parent rectangle a control is attached to: "stick to the top left of the screen," "fill the whole screen," "stretch across the top edge," and so on. Even when the window changes size, the UI follows along without drifting out of place. In the Inspector, under Layout → Anchors Preset, you can pick from the most common shapes. This lesson uses these three:

  • Full Rect: fills the whole parent (backgrounds, full-screen layouts)
  • Top Wide: sticks to the top edge and stretches all the way across (the HUD bar)
  • Center: sits in the middle

The other key idea is containers. A VBoxContainer lines up its children vertically, an HBoxContainer horizontally, a CenterContainer puts its children in the middle, and a MarginContainer adds padding around them. The container decides the position and size of its children, so you don't have to type in coordinates yourself.

Remember values across scenes with an Autoload

In this lesson, we'll switch between three scenes: the title, the game, and the result. The catch is that when you switch scenes, every node in the previous scene is deleted, variables and all. Even if you store the score in main.gd's score, it disappears the moment you move to the result screen.

That's what an Autoload is for. A script you register in Project Settings is created once when the game starts, isn't deleted when you switch scenes, and can be called by name from any script.

  1. In the FileSystem dock, right-click res:// → Create New → Script..., set Inherits to Node and the path to res://game_state.gd, and create it.
  2. Write the following and save.
game_state.gd
extends Node

# Register this script as an Autoload named GameState.
# Any scene can use it like GameState.score, and it isn't deleted when the scene changes

# Number of lives at the start of a game
const START_LIVES: int = 3

# Number of coins collected in this run
var score: int = 0
# Lives remaining
var lives: int = START_LIVES
# Whether the last run was cleared (used by the result screen)
var cleared: bool = false
# Time of the last run (seconds)
var last_time: float = 0.0
# Fastest clear time (seconds). 0.0 means there's no record yet
var best_time: float = 0.0


# Call this when starting a new game. Only the best time is kept
func reset() -> void:
	score = 0
	lives = START_LIVES
	cleared = false
	last_time = 0.0


# Call this when the game ends. If it was cleared, update the best time
func finish(is_clear: bool, time: float) -> void:
	cleared = is_clear
	last_time = time
	if is_clear and (best_time == 0.0 or time < best_time):
		best_time = time
  • const declares a constant (a value that never changes later). Giving a name to a number you set once and leave alone, like the starting number of lives, means you only have to change one place when you tweak it later.
  • reset() is called when a game starts, and finish() when it ends. Keeping the ways these values change inside GameState itself makes it easier to follow what changes where.

Next, register this script as an Autoload.

  1. Open Project → Project Settings... from the menu and select the Autoload tab.
  2. Click the folder icon to the right of the Path: field and choose res://game_state.gd. Check that Node Name: says GameState, then click Add.
  3. GameState is added to the list. If Enable is checked in the Global Variable column, you're done.

Once it's registered, the following lines are written to project.godot. The * in front of the path marks it as "use as a global variable."

project.godot (excerpt)
[autoload]

GameState="*res://game_state.gd"

Now any script can say GameState.score or GameState.reset(). While the game is running, a node called GameState sits under the very top of the scene tree (/root), with the current scene right next to it. Switching scenes only swaps out the current scene, so GameState stays put.

Don't put everything in an Autoload

Autoloads are handy, but when you have too many variables that anything can change from anywhere, it gets hard to tell "where did this change?" The trick is to store only the values you need to keep across scenes. Here, that's just the score, lives, result, and best time.

Rebuild the HUD with containers

The information shown during play (score, lives left, and so on) is called the HUD. In Lesson 6, we placed ScoreLabel inside HUD (a CanvasLayer) using coordinates. Children of a CanvasLayer stay in the same spot on screen even when the camera moves. This time we're going up to three readouts, so we'll lay them out again with containers.

  1. Open main.tscn and delete ScoreLabel under HUD. Since we're making a title screen, also delete the Title (Label) we put in the top left of the stage.
  2. Add a MarginContainer as a child of HUD and name it TopBar. In the Inspector, set Layout → Anchors Preset to Top Wide. You now have a bar stretching across the top edge of the screen.
  3. Under TopBar's Theme Overrides → Constants, set Margin Left to 24, Margin Top to 16, and Margin Right to 24 (the padding on the left, top, and right).
  4. Add an HBoxContainer as a child of TopBar and name it Row.
  5. Add three Label nodes as children of Row and name them ScoreLabel, TimeLabel, and LivesLabel. For all three, set Theme Overrides → Font Sizes → Font Size to 32, and under Layout → Container Sizing → Horizontal, check Expand.
  6. Set Horizontal Alignment to Center for TimeLabel and Right for LivesLabel (leave ScoreLabel at Left). Set their Text to Coins: 0 / 6, Time: 0.0, and Lives: 3 (the code rewrites these when the game runs).
HUD structure
HUD (CanvasLayer)
└─ TopBar (MarginContainer)  … Top Wide
    └─ Row (HBoxContainer)
        ├─ ScoreLabel (Label)  … left-aligned
        ├─ TimeLabel (Label)   … centered
        └─ LivesLabel (Label)  … right-aligned
main.tscn open with TopBar under HUD selected. Along the top edge of the screen, "Coins: 0 / 6," "Time: 0.0," and "Lives: 3" sit at the left, center, and right, and the Inspector's Anchors Preset is set to Top Wide
Setting TopBar to Top Wide gives you a bar that stretches across the top edge of the screen

Children with Expand checked split the width of the HBoxContainer equally. Each of the three labels gets one third of the width and aligns left, center, or right within it, so they line up neatly at the left edge, middle, and right edge of the screen. That layout holds even when the window width changes.

Lives, time, clearing the stage, and game over

Let's set the rules: collect every coin to clear the stage, and get hit by enemies 3 times and it's game over. The faster your clear time, the better your record.

Add a hit signal to the player

To tell Main that "the player touched an enemy," we'll give the player its own signal, just like in Lesson 6. Here's the whole player.gd (what changed is signal hit and the hit.emit() inside respawn()):

player.gd
extends CharacterBody2D

# Signal emitted when we touch an enemy
signal hit

# Left/right movement speed (pixels per second)
@export var speed: float = 300.0

# Gravity strength: the downward speed increases by this much every second
@export var gravity: float = 1200.0

# Speed at the moment of the jump. Up on screen is negative, so this is a negative value
@export var jump_velocity: float = -600.0

# Starting position (we come back here after touching an enemy)
var start_position: Vector2 = Vector2.ZERO


func _ready() -> void:
	start_position = position


# Called on every physics step (60 times per second by default)
func _physics_process(delta: float) -> void:
	# When not standing on the floor, increase the downward speed a little at a time (this is gravity)
	if not is_on_floor():
		velocity.y += gravity * delta

	# The moment the jump button is pressed, jump if we're on the floor
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = jump_velocity

	# If the button is released while still rising, halve the upward speed (short hop)
	if Input.is_action_just_released("jump") and velocity.y < 0.0:
		velocity.y *= 0.5

	# -1 for left, 1 for right, 0 if neither is pressed
	var direction: float = Input.get_axis("move_left", "move_right")
	velocity.x = direction * speed

	# Move according to velocity. If we hit a floor or wall, stop there
	move_and_slide()


# Send the player back to the start. Called by the enemy (enemy.gd)
func respawn() -> void:
	# Announce that we got hit (taking away a life is main.gd's job)
	hit.emit()
	position = start_position
	velocity = Vector2.ZERO

The player only announces "I got hit"; it doesn't know how many lives are left. Counting is Main's job. enemy.gd stays the same as in Lesson 6.

Rewrite main.gd

The score has moved into GameState, so the score variable in main.gd goes away. Replace the whole file with this:

main.gd
extends Node2D

# Number of coins on the stage (counted in _ready)
var coin_total: int = 0
# Time since the start (seconds)
var time: float = 0.0

# The HUD labels. With @onready, they get filled in right before _ready
@onready var score_label: Label = $HUD/TopBar/Row/ScoreLabel
@onready var time_label: Label = $HUD/TopBar/Row/TimeLabel
@onready var lives_label: Label = $HUD/TopBar/Row/LivesLabel


func _ready() -> void:
	# We're starting a new game, so reset the score and lives to their starting values
	GameState.reset()
	var coins: Array[Node] = get_tree().get_nodes_in_group("coins")
	coin_total = coins.size()
	# In code, connect the collected signal of every coin in the "coins" group
	for coin: Node in coins:
		coin.connect("collected", _on_coin_collected)
	# Also connect, in code, the hit signal the player emits when it touches an enemy
	$Player.connect("hit", _on_player_hit)
	update_hud()


func _process(delta: float) -> void:
	time += delta
	# %.1f is replaced by "the number with one decimal place"
	time_label.text = "Time: %.1f" % time


# Called when any coin emits its collected signal
func _on_coin_collected() -> void:
	GameState.score += 1
	update_hud()
	# Collecting every coin clears the stage
	if GameState.score == coin_total:
		end_game(true)


# Called when the player emits its hit signal
func _on_player_hit() -> void:
	GameState.lives -= 1
	update_hud()
	# When lives reach 0, it's game over
	if GameState.lives <= 0:
		end_game(false)


func update_hud() -> void:
	# %d is replaced by a whole number. For two or more, pass them in a [ ] list
	score_label.text = "Coins: %d / %d" % [GameState.score, coin_total]
	lives_label.text = "Lives: " + str(GameState.lives)


# End the game and switch to the result screen
func end_game(is_clear: bool) -> void:
	GameState.finish(is_clear, time)
	# Changing scenes in the middle of physics processing causes an error, so call_deferred puts it off a moment
	get_tree().change_scene_to_file.call_deferred("res://result.tscn")
  • We call GameState.reset() at the very start of _ready. When you come back with "Play Again," this is also where the score and lives go back to their starting values.
  • coin_total is the number of coins in the group. Whether you add or remove coins, the "collect them all to clear" check doesn't need to change.
  • "Time: %.1f" % time is string formatting. The %.1f in the string is replaced by time rounded to one decimal place. %d is for whole numbers; to fill in two or more, pass them in a [ ] list.
  • get_tree().change_scene_to_file("res://result.tscn") switches scenes. The current scene (Main) is removed and replaced by the scene you specify.
  • When you grab the last coin or touch an enemy, the physics engine is in the middle of working out "what overlapped what." Removing the scene partway through causes an error, so we add call_deferred to switch "after the current processing finishes."

Make a title screen

Now we'll make a new scene that's nothing but UI.

  1. Choose Scene → New Scene, and under Create Root Node: in the Scene dock, click User Interface. A Control is created as the root; name it Title. The root's Anchors Preset is already Full Rect (fills the screen).
  2. Add a ColorRect as a child of Title and name it Background. Set its Anchors Preset to Full Rect and its Color to the same light blue as the game's sky (669ed9).
  3. Add a CenterContainer as a child of Title, name it Center, and set its Anchors Preset to Full Rect too.
  4. Add a VBoxContainer as a child of Center and name it Menu. Set Theme Overrides → Constants → Separation to 24 (the spacing between items).
  5. Add these four to Menu, in order:
    • Label (name TitleLabel): Text Hop Hop Coins, Horizontal Alignment Center, Font Size 64
    • TextureRect (name Icon): Texture icon.svg, Stretch Mode Keep Centered
    • Label (name BestLabel): Text Collect all the coins!, Horizontal Alignment Center, Font Size 28
    • Button (name StartButton): Text Start, Font Size 32, Layout → Custom Minimum Size 240, 64, and Container Sizing → Horizontal set to Shrink Center (so the button doesn't stretch across the full width and sits in the middle)
  6. Save it as res://title.tscn.
title.tscn structure
Title (Control)  … title.gd
├─ Background (ColorRect)  … Full Rect
└─ Center (CenterContainer)  … Full Rect
    └─ Menu (VBoxContainer)
        ├─ TitleLabel (Label)
        ├─ Icon (TextureRect)
        ├─ BestLabel (Label)
        └─ StartButton (Button)
title.tscn open with Center (CenterContainer) selected. The title, character, description text, and Start button are stacked vertically in the middle of the screen, and the Inspector's Anchors Preset is set to Full Rect
Put things in a VBoxContainer inside a CenterContainer and they stack vertically in the middle, no coordinates needed

Connect the button's pressed signal

A button emits the pressed signal when it's pressed. We'll connect it in the editor, just like the coin in Lesson 6.

  1. Right-click Title → Attach Script to create res://title.gd.
  2. Select StartButton, and in the Signals tab of the dock on the right, double-click pressed() under BaseButton.
  3. In Connect a Signal to a Method, choose Title as the target, check that Receiver Method: is _on_start_button_pressed, and click Connect.
title.gd
extends Control

@onready var best_label: Label = $Center/Menu/BestLabel
@onready var start_button: Button = $Center/Menu/StartButton


func _ready() -> void:
	# GameState isn't deleted when the scene changes, so the record from the last run is still there
	if GameState.best_time > 0.0:
		best_label.text = "Best time: %.1f s" % GameState.best_time
	else:
		best_label.text = "Collect all the coins!"
	# Giving the button focus lets you press it with the Space or Enter key too
	start_button.grab_focus()


# Called when the "Start" button is pressed (connected in the editor's "Signals" tab)
func _on_start_button_pressed() -> void:
	get_tree().change_scene_to_file("res://main.tscn")
  • You receive a button click as a signal that says "I was pressed." A button can be pressed with the mouse or the keyboard, and pressed fires the same way either way.
  • grab_focus() points keyboard input at that button. A button with focus can be pressed with the Enter key or the Space key.
  • If a best time has been recorded, we show it. When you come back to the title the second time or later, GameState is still around, so the previous record can be read.

The result screen and retrying

We'll use one result screen for both clearing the stage and game over, just changing what it shows. Building it works almost exactly like the title screen.

  1. Create a new scene, click User Interface, and name the root Result.
  2. Just like the title, make Background (ColorRect, Full Rect, Color navy 333d66), Center (CenterContainer, Full Rect), and Menu (VBoxContainer, Separation 24).
  3. Add two Label nodes to Menu (ResultLabel with Font Size 64 and DetailLabel with Font Size 28, both with Horizontal Alignment Center) and two Button nodes (RetryButton with Text Play Again and TitleButton with Text Back to Title, both with the same size and settings as the Start button).
  4. Save it as res://result.tscn and attach the script res://result.gd to Result.
  5. Connect the pressed() signals of RetryButton and TitleButton to Result's _on_retry_button_pressed and _on_title_button_pressed, respectively.
result.gd
extends Control

@onready var result_label: Label = $Center/Menu/ResultLabel
@onready var detail_label: Label = $Center/Menu/DetailLabel
@onready var retry_button: Button = $Center/Menu/RetryButton


func _ready() -> void:
	# GameState still remembers how the run went
	if GameState.cleared:
		result_label.text = "Stage Clear!"
		detail_label.text = "Time: %.1f s (Best: %.1f s)" % [GameState.last_time, GameState.best_time]
	else:
		result_label.text = "Game Over"
		detail_label.text = "Coins collected: %d" % GameState.score
	retry_button.grab_focus()


# "Play Again" button: start the game scene over from the beginning
func _on_retry_button_pressed() -> void:
	get_tree().change_scene_to_file("res://main.tscn")


# "Back to Title" button: return to the title screen
func _on_title_button_pressed() -> void:
	get_tree().change_scene_to_file("res://title.tscn")

This is where the Autoload really shines. main.tscn is already gone, yet reading GameState.cleared and GameState.score tells us how the run went. When "Play Again" loads main.tscn again, the stage starts fresh, and main.gd's _ready resets the score and lives.

The result screen. In the middle of a navy background, the text "Game Over" and "Coins collected: 0" appear, with two buttons, "Play Again" and "Back to Title"
The result screen after a game over. The focused "Play Again" button has a white outline

Make the title screen the main scene

The scene that opens first when you press F5 (Run Project) is called the main scene. Right now it's main.tscn, so let's change it to the title screen.

  1. In the FileSystem dock, right-click title.tscn and choose Set as Main Scene.

You can also change it under Application → Run → Main Scene in Project Settings.... If run/main_scene in project.godot becomes "res://title.tscn", you're all set.

Run it with F5. Press Start on the title screen and the game begins, with the coin count, time, and lives lined up along the top edge. Collect all six coins to get the clear screen, or get hit by enemies three times to get the game over screen; "Play Again" lets you try again. If you clear the stage and then go back to the title, your best time should be displayed.

The game screen. Along the top edge, "Coins: 1 / 6" is on the left, "Time: 2.9" in the middle, and "Lives: 3" on the right
The three HUD readouts now line the top edge. They stay put even when the camera scrolls

Here's the flow between scenes so far:

Screen flow
title.tscn ──Start──→ main.tscn ──all coins──→ result.tscn (Stage Clear!)
     ↑                    │                         │
     │                    └──0 lives──→ result.tscn (Game Over)
     │                                              │
     └──────────Back to Title───────────────────────┤
                          main.tscn ←──Play Again───┘

(The whole time, GameState remembers score / lives / best_time)
Try it
  • Set START_LIVES in game_state.gd to 1 and see how the tension changes.
  • Add a "How to play" Label to the title screen ("← → to move, Space to jump"). Just put it inside Menu and it lines up automatically.
  • Drag the edge of the window to resize it. You'll see the HUD and title screen follow their anchors.

Common pitfalls

SymptomCause and fix
Identifier "GameState" not declared in the current scope.It isn't registered as an Autoload, or the node name is different. In the Autoload tab, check that the node name is GameState (including upper/lower case) and that Enable is checked.
Removing a CollisionObject node during a physics callback is not allowed and will cause undesired behavior. at the moment you clear the stage or get a game overYou're switching scenes inside a signal, in the middle of physics processing. Add call_deferred, as in change_scene_to_file.call_deferred(...).
Nothing happens when you press a buttonThe pressed() signal isn't connected. In the Signals tab, check that the target method appears under pressed().
The HUD labels pile up in the top leftIf Expand isn't checked under the label's Container Sizing → Horizontal, the labels don't share the width and get squeezed to the left. Check it on all three.
The background only covers part of the screenThe ColorRect's Anchors Preset isn't Full Rect. Also check that the parent Title is Full Rect.
F5 starts on the stage instead of the titleThe main scene is still main.tscn. Use Set as Main Scene on title.tscn. Note that F6 (Run Current Scene) starts from whichever scene is open.
On your second play, you start with fewer livesYou aren't calling GameState.reset() in main.gd's _ready. Autoload values stick around until you reset them yourself.

Working with AI

If you hand this lesson's work to AI

For UI, decide up front "what goes on which screen, and where" and "which button goes to which screen," and your requests to AI won't drift. Handing over something like the "Screen flow" diagram above as is works well.

This is Godot 4.6. Create an Autoload named GameState (res://game_state.gd, extends Node). It should hold score, lives (3 at the start), cleared, last_time, and best_time, and change them through reset() and finish(is_clear, time). best_time is the fastest clear time; don't clear it in reset().
Create title.tscn. The root is a Control (Full Rect) with a ColorRect background (Full Rect) and a CenterContainer (Full Rect) as children, and inside that a VBoxContainer holding the title Label, BestLabel, and StartButton. Switch to main.tscn on StartButton's pressed signal. Don't use coordinates; lay it out with anchors and containers.
  • A (chat): it's good at screen layouts, how scene transitions fit together, and writing the scripts. You add the nodes, set the anchors, and register the Autoload in the editor yourself. If things look off, pasting a screenshot makes the problem easier to get across.
  • B (Claude Code, etc.): it can write .tscn and project.godot files too, so it can build the scenes and register the Autoload in one go. But if it rewrites project.godot while the editor is open, the editor may overwrite the change and it's lost. Also, the AI can't see how the UI actually looks.
  • C (+ MCP): with Godot MCP Pro, the AI can register the Autoload (add_autoload), set anchors (set_anchor_preset), and connect button signals (connect_signal) inside the editor. You can leave it to run the game, press buttons (click_button_by_text), check the text on screen (assert_screen_text), and look at the result in a screenshot (get_game_screenshot).

Whichever approach you use, play it yourself at the end to check. Text size and color, and how easy the buttons are to press, are things you decide by actually looking and touching.

Recap and what's next

  • Build UI from the Control family. Set placement with Anchors Preset (Full Rect, Top Wide, and so on)
  • Put children in a container (VBox, HBox, Center, Margin) and they line up automatically
  • A node registered as an Autoload isn't deleted when scenes change and can be used by name from anywhere
  • Switch scenes with get_tree().change_scene_to_file(). During physics processing, use call_deferred
  • Receive button presses with the pressed signal. grab_focus() makes the button pressable from the keyboard
  • Change the main scene with Set as Main Scene

Now you can play one full "loop" of the game. Next time: sound and game feel. We'll use sound effects, BGM, Tweens, and particles to make grabbing a coin feel great.

Want AI to handle building the UI and checking screen transitions?

With Godot MCP Pro, Claude Code or Cursor can set up Control node anchors and Autoloads inside the editor, run the game, press buttons, and even check the text on screen (190 tools, $15 one-time purchase). You can finish this series without MCP.

Learn more about Godot MCP Pro · The complete guide to signals in Godot 4

All lessons in the series (11)
  1. Lesson 1: Installing Godot and setting up AI tools
  2. Lesson 2: Nodes and scenes
  3. Lesson 3: GDScript basics
  4. Lesson 4: Input and player movement
  5. Lesson 5: Gravity, jumping, and tilemaps
  6. Lesson 6: Signals, coins, and enemies
  7. Lesson 7: UI and screen transitionsYou are here
  8. Lesson 8: Sound and game feel
  9. Lesson 9: Letting AI playtest your game
  10. Lesson 10: Exporting and publishing
  11. Lesson 11: Bonus: one-prompt games by genre