Global Data via Autorun

It’s common to want some data to persist across your entire game. By default, most data is attached to the scene and thus goes away when the scene goes away. So then, how do we create data that is available during the entire lifecycle of our games? We use autoloads.

First, we need to create a GDScript file. Switch to the Script tab, then select File->New Script.

New-Script Godot Screenshot

Name the file (or whatever name you prefer, so long as it has the .gd extension). Next enter the following code:

extends Node

var currentStage = 1
var kills = 0

This code is simply declaring two global variables, currentStage and kills. The script MUST extend Node or it won’t be loaded. Speaking of loaded, now we have to tell Godot to load this script when our game starts. Now go back to the Project->Project Settings menu, then select the AutoLoad tab.

Click the folder icon to the right of the Path field and select our newly created

Setting-up-an-AutoLoad Godot Screenshot

Finally, click the Add button and you should see:

Global-Added Godot Screenshot

Now that we have a couple of global variables available, let’s reset these values when the title scene is loaded. This is useful, as it will reset our game when we return to the title scene later on. Open up the TitleScene in the 2D view if it isn’t already. Now we will attach a script to the root control in our scene. Select the root control, then click the + script icon to the right to create a new script.

Attach-a-script in Godot Screenshot

The default values are all fine, simply click Create.

Create-Script in Godot Screenshot

The code should open automatically (if not, you can open it by clicking the scroll icon to the right of the control the script is attached to). Edit the code to consist of the following:

extends Control

func _ready():
  globals.kills = 0
  globals.currentStage = 0

As you can see we can access the global variables we created by entering the Node Name we specified in the AutoLoads, followed by a period and the variable name. While trivial in this example, global variables can be extremely useful, but be careful not to abuse them!


Scroll to Top