Autoload

This guide assumes you’ve already completed the guides More Levels and Portals.

Currently, when we change level, the coins collected get reset to 0.

If we want to keep track of this - and potentially other things - across levels, we can use an autoload.

In Godot, an Autoload is a scene or script that gets loaded automatically (hence the name), and unlike regular scenes it doesn’t get unloaded when changing scenes.

For background, see the Godot docs on Singletons (Autoload).

In our little game, we’ll add an autoload for keeping track of the number of coins collected across scenes.

We will now move the HUD from the individual level scenes to the Game scenes.

Your Game scene should now look like this:

Scene Tree

extends Node

var coins := 0

func collect_coin():
	coins += 1
	$HUD/Coins.text = str(coins)

Autoloading game.tscn

It should look like this now:

Project Settings/Autoload

If you test your game now, you’ll notice that the HUD appears on all levels even though you deleted the HUD from each scene. It doesn’t actually count coins, though. Let’s fix that.

Fixing Coin Counting

The reason it doesn’t work now is that previously we relied on var coins in player.gd and this got updated from coin.gd via a signla. This still happens, but since we moved the hud, it no longer listens for the coins_collected signal.

We’ll do this a slightly different way now.

func _on_body_entered(body):
	if body.has_method("collect_coin") and !grabbed:
		
		body.collect_coin()

to this:

func _on_body_entered(body):
	if !grabbed:
		
		Game.collect_coin()

Notice that we’re no longer checking if body has the collect_coin method. This was a convenient way to ensure that we’re only reacting to the Player grabbing coins.

This means that we can now get in a situation where other bodies (like platforms) touch the coin collision shape and thereby “grab” the coins.

To prevent that, follow the steps in the Collision Masks guide, if you haven’t already.