We’d love to hear from you. Whether you have a question that you’d like us to answer as part of our FAQ,  you’ve identified something that just doesn’t quite look right in one of our tutorials, you have a business opportunity or for any other reason, please use this simple form to contact us.

We’ll do our best to provide a prompt response.

Like it? Pass it on!

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.


Name the file globals.gd (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 globals.gd.


Finally, click the Add button and you should see:


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.


The default values are all fine, simply click Create.


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!

Playing Background Music<<PreviousTable of ContentsNext>>Creating a Simple UI

Like it? Pass it on!
script ends --->