GDScript basics

Introduction

GDScript is a high level, dynamically typed programming language used to create content. It uses a syntax similar to Python (blocks are indent-based and many keywords are similar). Its goal is to be optimized for and tightly integrated with Godot Engine, allowing great flexibility for content creation and integration.

History

In the early days, the engine used the Lua scripting language. Lua is fast, but creating bindings to an object oriented system (by using fallbacks) was complex and slow and took an enormous amount of code. After some experiments with Python, it also proved difficult to embed.

The last third party scripting language that was used for shipped games was Squirrel, but it was dropped as well. At that point, it became evident that a custom scripting language could more optimally make use of Godot’s particular architecture:

  • Godot embeds scripts in nodes. Most languages are not designed with this in mind.
  • Godot uses several built-in data types for 2D and 3D math. Script languages do not provide this, and binding them is inefficient.
  • Godot uses threads heavily for lifting and initializing data from the net or disk. Script interpreters for common languages are not friendly to this.
  • Godot already has a memory management model for resources, most script languages provide their own, which results in duplicate effort and bugs.
  • Binding code is always messy and results in several failure points, unexpected bugs and generally low maintainability.

The result of these considerations is GDScript. The language and interpreter for GDScript ended up being smaller than the binding code itself for Lua and Squirrel, while having equal functionality. With time, having a built-in language has proven to be a huge advantage.

Example of GDScript

Some people can learn better by taking a look at the syntax, so here’s a simple example of how GDScript looks.

  1. # A file is a class!
  2. # Inheritance
  3. extends BaseClass
  4. # (optional) class definition with a custom icon
  5. class_name MyClass, "res://path/to/optional/icon.svg"
  6. # Member Variables
  7. var a = 5
  8. var s = "Hello"
  9. var arr = [1, 2, 3]
  10. var dict = {"key": "value", 2:3}
  11. var typed_var: int
  12. var inferred_type := "String"
  13. # Constants
  14. const ANSWER = 42
  15. const THE_NAME = "Charly"
  16. # Enums
  17. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  18. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  19. # Built-in Vector Types
  20. var v2 = Vector2(1, 2)
  21. var v3 = Vector3(1, 2, 3)
  22. # Function
  23. func some_function(param1, param2):
  24. var local_var = 5
  25. if param1 < local_var:
  26. print(param1)
  27. elif param2 > 5:
  28. print(param2)
  29. else:
  30. print("Fail!")
  31. for i in range(20):
  32. print(i)
  33. while param2 != 0:
  34. param2 -= 1
  35. var local_var2 = param1 + 3
  36. return local_var2
  37. # Functions override functions with the same name on the base/parent class.
  38. # If you still want to call them, use '.' (like 'super' in other languages).
  39. func something(p1, p2):
  40. .something(p1, p2)
  41. # Inner Class
  42. class Something:
  43. var a = 10
  44. # Constructor
  45. func _init():
  46. print("Constructed!")
  47. var lv = Something.new()
  48. print(lv.a)

If you have previous experience with statically typed languages such as C, C++, or C# but never used a dynamically typed one before, it is advised you read this tutorial: GDScript: An introduction to dynamic languages.

Language

In the following, an overview is given to GDScript. Details, such as which methods are available to arrays or other objects, should be looked up in the linked class descriptions.

Identifiers

Any string that restricts itself to alphabetic characters (a to z and A to Z), digits (0 to 9) and _ qualifies as an identifier. Additionally, identifiers must not begin with a digit. Identifiers are case-sensitive (foo is different from FOO).

Keywords

The following is the list of keywords supported by the language. Since keywords are reserved words (tokens), they can’t be used as identifiers. Operators (like in, not, and or or) and names of built-in types as listed in the following sections are also reserved.

Keywords are defined in the GDScript tokenizer in case you want to take a look under the hood.

KeywordDescription
ifSee if/else/elif.
elifSee if/else/elif.
elseSee if/else/elif.
forSee for.
whileSee while.
matchSee match.
breakExits the execution of the current for or while loop.
continueImmediately skips to the next iteration of the for or while loop.
passUsed where a statement is required syntactically but execution of code is undesired, e.g. in empty functions.
returnReturns a value from a function.
classDefines a class.
extendsDefines what class to extend with the current class.
isTests whether a variable extends a given class, or is of a given built-in type.
asCast the value to a given type if possible.
selfRefers to current class instance.
toolExecutes the script in the editor.
signalDefines a signal.
funcDefines a function.
staticDefines a static function. Static member variables are not allowed.
constDefines a constant.
enumDefines an enum.
varDefines a variable.
onreadyInitializes a variable once the Node the script is attached to and its children are part of the scene tree.
exportSaves a variable along with the resource it’s attached to and makes it visible and modifiable in the editor.
setgetDefines setter and getter functions for a variable.
breakpointEditor helper for debugger breakpoints.
preloadPreloads a class or variable. See Classes as resources.
yieldCoroutine support. See Coroutines with yield.
assertAsserts a condition, logs error on failure. Ignored in non-debug builds. See Assert keyword.
remoteNetworking RPC annotation. See high-level multiplayer docs.
masterNetworking RPC annotation. See high-level multiplayer docs.
puppetNetworking RPC annotation. See high-level multiplayer docs.
remotesyncNetworking RPC annotation. See high-level multiplayer docs.
mastersyncNetworking RPC annotation. See high-level multiplayer docs.
puppetsyncNetworking RPC annotation. See high-level multiplayer docs.
PIPI constant.
TAUTAU constant.
INFInfinity constant. Used for comparisons.
NANNAN (not a number) constant. Used for comparisons.

Operators

The following is the list of supported operators and their precedence.

OperatorDescription
x[index]Subscription, Highest Priority
x.attributeAttribute Reference
isInstance Type Checker
~Bitwise NOT
-xNegative / Unary Negation
/ %

Multiplication / Division / Remainder

These operators have the same behavior as C++. Integer division is truncated rather than returning a fractional number, and the % operator is only available for ints (“fmod” for floats)

+Addition / Concatenation of Arrays
-Subtraction
<< >>Bit Shifting
&Bitwise AND
^Bitwise XOR
|Bitwise OR
< > == != >= <=Comparisons
inContent Test
! notBoolean NOT
and &&Boolean AND
or ||Boolean OR
if x elseTernary if/else
= += -= = /= %= &= |=Assignment, Lowest Priority

Literals

LiteralType
45Base 10 integer
0x8F51Base 16 (hex) integer
3.14, 58.1e-10Floating point number (real)
“Hello”, “Hi”Strings
“””Hello”””Multiline string
@”Node/Label”NodePath or StringName
$NodePathShorthand for get_node(“NodePath”)

Comments

Anything from a # to the end of the line is ignored and is considered a comment.

  1. # This is a comment.

Multi-line comments can be created using “”” (three quotes in a row) at the beginning and end of a block of text. Note that this creates a string, therefore, it will not be stripped away when the script is compiled.

  1. """ Everything on these
  2. lines is considered
  3. a comment. """

Built-in types

Built-in types are stack-allocated. They are passed as values. This means a copy is created on each assignment or when passing them as arguments to functions. The only exceptions are Arrays and Dictionaries, which are passed by reference so they are shared. (Not PoolArrays like PoolByteArray though, those are passed as values too, so consider this when deciding which to use!)

Basic built-in types

A variable in GDScript can be assigned to several built-in types.

null

null is an empty data type that contains no information and can not be assigned any other value.

bool

The Boolean data type can only contain true or false.

int

The integer data type can only contain integer numbers, (both negative and positive).

float

Used to contain a floating point value (real numbers).

String

A sequence of characters in Unicode format. Strings can contain the standard C escape sequences. GDScript supports format strings aka printf functionality.

Vector built-in types

Vector2

2D vector type containing x and y fields. Can also be accessed as array.

Rect2

2D Rectangle type containing two vectors fields: position and size. Alternatively contains an end field which is position+size.

Vector3

3D vector type containing x, y and z fields. This can also be accessed as an array.

Transform2D

3x2 matrix used for 2D transforms.

Plane

3D Plane type in normalized form that contains a normal vector field and a d scalar distance.

Quat

Quaternion is a datatype used for representing a 3D rotation. It’s useful for interpolating rotations.

AABB

Axis-aligned bounding box (or 3D box) contains 2 vectors fields: position and size. Alternatively contains an end field which is position+size.

Basis

3x3 matrix used for 3D rotation and scale. It contains 3 vector fields (x, y and z) and can also be accessed as an array of 3D vectors.

Transform

3D Transform contains a Basis field basis and a Vector3 field origin.

Engine built-in types

Color

Color data type contains r, g, b, and a fields. It can also be accessed as h, s, and v for hue/saturation/value.

NodePath

Compiled path to a node used mainly in the scene system. It can be easily assigned to, and from, a String.

RID

Resource ID (RID). Servers use generic RIDs to reference opaque data.

Object

Base class for anything that is not a built-in type.

Container built-in types

Array

Generic sequence of arbitrary object types, including other arrays or dictionaries (see below). The array can resize dynamically. Arrays are indexed starting from index 0. Starting with Godot 2.1, indices may be negative like in Python, to count from the end.

  1. var arr = []
  2. arr = [1, 2, 3]
  3. var b = arr[1] # This is 2.
  4. var c = arr[arr.size() - 1] # This is 3.
  5. var d = arr[-1] # Same as the previous line, but shorter.
  6. arr[0] = "Hi!" # Replacing value 1 with "Hi!".
  7. arr.append(4) # Array is now ["Hi!", 2, 3, 4].

GDScript arrays are allocated linearly in memory for speed. Large arrays (more than tens of thousands of elements) may however cause memory fragmentation. If this is a concern, special types of arrays are available. These only accept a single data type. They avoid memory fragmentation and also use less memory but are atomic and tend to run slower than generic arrays. They are therefore only recommended to use for large data sets:

Dictionary

Associative container which contains values referenced by unique keys.

  1. var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
  2. d["Hi!"] = 0
  3. d = {
  4. 22: "value",
  5. "some_key": 2,
  6. "other_key": [2, 3, 4],
  7. "more_key": "Hello"
  8. }

Lua-style table syntax is also supported. Lua-style uses = instead of : and doesn’t use quotes to mark string keys (making for slightly less to write). Note however that like any GDScript identifier, keys written in this form cannot start with a digit.

  1. var d = {
  2. test22 = "value",
  3. some_key = 2,
  4. other_key = [2, 3, 4],
  5. more_key = "Hello"
  6. }

To add a key to an existing dictionary, access it like an existing key and assign to it:

  1. var d = {} # Create an empty Dictionary.
  2. d.waiting = 14 # Add String "waiting" as a key and assign the value 14 to it.
  3. d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
  4. d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.

Data

Variables

Variables can exist as class members or local to functions. They are created with the var keyword and may, optionally, be assigned a value upon initialization.

  1. var a # Data type is 'null' by default.
  2. var b = 5
  3. var c = 3.8
  4. var d = b + c # Variables are always initialized in order.

Variables can optionally have a type specification. When a type is specified, the variable will be forced to have always that same type, and trying to assign an incompatible value will raise an error.

Types are specified in the variable declaration using a : (colon) symbol after the variable name, followed by the type.

  1. var my_vector2: Vector2
  2. var my_node: Node = Sprite.new()

If the variable is initialized within the declaration, the type can be inferred, so it’s possible to omit the type name:

  1. var my_vector2 := Vector2() # 'my_vector2' is of type 'Vector2'
  2. var my_node := Sprite.new() # 'my_node' is of type 'Sprite'

Type inference is only possible if the assigned value has a defined type, otherwise it will raise an error.

Valid types are:

  • Built-in types (Array, Vector2, int, String, etc.)
  • Engine classes (Node, Resource, Reference, etc.)
  • Constant names if they contain a script resource (MyScript if you declared const MyScript = preload("res://my_script.gd")).
  • Other classes in the same script, respecting scope (InnerClass.NestedClass if you declared class NestedClass inside the class InnerClass in the same scope)
  • Script classes declared with the class_name keyword.

Casting

Values assigned to typed variables must have a compatible type. If it’s needed to coerce a value to be of a certain type, in particular for object types, you can use the casting operator as.

Casting between object types results in the same object if the value is of the same type or a subtype of the cast type.

  1. var my_node2D: Node2D
  2. my_node2D = $Sprite as Node2D # Works since Sprite is a subtype of Node2D

If the value is not a subtype, the casting operation will result in a null value.

  1. var my_node2D: Node2D
  2. my_node2D = $Button # Results in 'null' since a Button is not a subtype of Node2D

For built-in types, they will be forcibly converted if possible, otherwise the engine will raise an error.

  1. var my_int: int
  2. my_int = "123" as int # The string can be converted to int
  3. my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error

Casting is also useful to have better type-safe variables when interacting with tree:

  1. # will infer the variable to be of type Sprite:
  2. var my_sprite := $Character as Sprite
  3. # will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()':
  4. ($AnimPlayer as AnimationPlayer).play("walk")

Constants

Constants are similar to variables, but must be constants or constant expressions and must be assigned on initialization.

  1. const A = 5
  2. const B = Vector2(20, 20)
  3. const C = 10 + 20 # Constant expression.
  4. const D = Vector2(20, 30).x # Constant expression: 20
  5. const E = [1, 2, 3, 4][0] # Constant expression: 1
  6. const F = sin(20) # sin() can be used in constant expressions.
  7. const G = x + 20 # Invalid; this is not a constant expression!
  8. const H = A + 20 # Constant expression: 25

Although the type of constants is inferred from the assigned value, it’s also possible to add explicit type specification:

  1. const A: int = 5
  2. const B: Vector2 = Vector2()

Assigning a value of an incompatible type will raise an error.

Enums

Enums are basically a shorthand for constants, and are pretty useful if you want to assign consecutive integers to some constant.

If you pass a name to the enum, it will put all the keys inside a constant dictionary of that name.

  1. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  2. # Is the same as:
  3. const TILE_BRICK = 0
  4. const TILE_FLOOR = 1
  5. const TILE_SPIKE = 2
  6. const TILE_TELEPORT = 3
  7. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  8. # Is the same as:
  9. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  10. # Access values with State.STATE_IDLE, etc.

Functions

Functions always belong to a class. The scope priority for variable look-up is: local → class member → global. The self variable is always available and is provided as an option for accessing class members, but is not always required (and should not be sent as the function’s first argument, unlike Python).

  1. func my_function(a, b):
  2. print(a)
  3. print(b)
  4. return a + b # Return is optional; without it 'null' is returned.

A function can return at any point. The default return value is null.

Functions can also have type specification for the arguments and for the return value. Types for arguments can be added in a similar way to variables:

  1. func my_function(a: int, b: String):
  2. pass

If a function argument has a default value, it’s possible to infer the type:

  1. func my_function(int_arg := 42, String_arg := "string"):
  2. pass

The return type of the function can be specified after the arguments list using the arrow token (->):

  1. func my_int_function() -> int:
  2. return 0

Functions that have a return type must return a proper value. Setting the type as void means the function doesn’t return anything. Void functions can return early with the return keyword, but they can’t return any value.

  1. void_function() -> void:
  2. return # Can't return a value

Note

Non-void functions must always return a value, so if your code has branching statements (such as an if/else construct), all the possible paths must have a return. E.g., if you have a return inside an if block but not after it, the editor will raise an error because if the block is not executed, the function won’t have a valid value to return.

Referencing Functions

Contrary to Python, functions are not first class objects in GDScript. This means they cannot be stored in variables, passed as an argument to another function or be returned from other functions. This is for performance reasons.

To reference a function by name at runtime, (e.g. to store it in a variable, or pass it to another function as an argument) one must use the call or funcref helpers:

  1. # Call a function by name in one step.
  2. my_node.call("my_function", args)
  3. # Store a function reference.
  4. var my_func = funcref(my_node, "my_function")
  5. # Call stored function reference.
  6. my_func.call_func(args)

Remember that default functions, like _init, and most notifications, such as _enter_tree, _exit_tree, _process, _physics_process, etc. are called in all base classes automatically. So there is only a need to call the function explicitly when overloading them in some way.

Static functions

A function can be declared static. When a function is static, it has no access to the instance member variables or self. This is mainly useful to make libraries of helper functions:

  1. static func sum2(a, b):
  2. return a + b

Statements and control flow

Statements are standard and can be assignments, function calls, control flow structures, etc (see below). ; as a statement separator is entirely optional.

if/else/elif

Simple conditions are created by using the if/else/elif syntax. Parenthesis around conditions are allowed, but not required. Given the nature of the tab-based indentation, elif can be used instead of else/if to maintain a level of indentation.

  1. if [expression]:
  2. statement(s)
  3. elif [expression]:
  4. statement(s)
  5. else:
  6. statement(s)

Short statements can be written on the same line as the condition:

  1. if 1 + 1 == 2: return 2 + 2
  2. else:
  3. var x = 3 + 3
  4. return x

Sometimes you might want to assign a different initial value based on a boolean expression. In this case, ternary-if expressions come in handy:

  1. var x = [value] if [expression] else [value]
  2. y += 3 if y < 10 else -1

while

Simple loops are created by using while syntax. Loops can be broken using break or continued using continue:

  1. while [expression]:
  2. statement(s)

for

To iterate through a range, such as an array or table, a for loop is used. When iterating over an array, the current array element is stored in the loop variable. When iterating over a dictionary, the index is stored in the loop variable.

  1. for x in [5, 7, 11]:
  2. statement # Loop iterates 3 times with 'x' as 5, then 7 and finally 11.
  3. var dict = {"a": 0, "b": 1, "c": 2}
  4. for i in dict:
  5. print(dict[i])
  6. for i in range(3):
  7. statement # Similar to [0, 1, 2] but does not allocate an array.
  8. for i in range(1,3):
  9. statement # Similar to [1, 2] but does not allocate an array.
  10. for i in range(2,8,2):
  11. statement # Similar to [2, 4, 6] but does not allocate an array.
  12. for c in "Hello":
  13. print(c) # Iterate through all characters in a String, print every letter on new line.

match

A match statement is used to branch execution of a program. It’s the equivalent of the switch statement found in many other languages, but offers some additional features.

Basic syntax:

  1. match [expression]:
  2. [pattern](s):
  3. [block]
  4. [pattern](s):
  5. [block]
  6. [pattern](s):
  7. [block]

Crash-course for people who are familiar with switch statements:

  1. Replace switch with match
  2. Remove case
  3. Remove any breaks. If you don’t want to break by default, you can use continue for a fallthrough.
  4. Change default to a single underscore.

Control flow:

The patterns are matched from top to bottom. If a pattern matches, the corresponding block will be executed. After that, the execution continues below the match statement. If you want to have a fallthrough, you can use continue to stop execution in the current block and check the ones below it.

There are 6 pattern types:

  • constant pattern

    constant primitives, like numbers and strings

    1. match x:
    2. 1:
    3. print("We are number one!")
    4. 2:
    5. print("Two are better than one!")
    6. "test":
    7. print("Oh snap! It's a string!")
  • variable pattern

    matches the contents of a variable/enum

    1. match typeof(x):
    2. TYPE_REAL:
    3. print("float")
    4. TYPE_STRING:
    5. print("text")
    6. TYPE_ARRAY:
    7. print("array")
  • wildcard pattern

    This pattern matches everything. It’s written as a single underscore.

    It can be used as the equivalent of the default in a switch statement in other languages.

    1. match x:
    2. 1:
    3. print("It's one!")
    4. 2:
    5. print("It's one times two!")
    6. _:
    7. print("It's not 1 or 2. I don't care tbh.")
  • binding pattern

    A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name. It’s especially useful in array and dictionary patterns.

    1. match x:
    2. 1:
    3. print("It's one!")
    4. 2:
    5. print("It's one times two!")
    6. var new_var:
    7. print("It's not 1 or 2, it's ", new_var)
  • array pattern

    matches an array. Every single element of the array pattern is a pattern itself, so you can nest them.

    The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern doesn’t match.

    Open-ended array: An array can be bigger than the pattern by making the last subpattern ..

    Every subpattern has to be comma separated.

    1. match x:
    2. []:
    3. print("Empty array")
    4. [1, 3, "test", null]:
    5. print("Very specific array")
    6. [var start, _, "test"]:
    7. print("First element is ", start, ", and the last is \"test\"")
    8. [42, ..]:
    9. print("Open ended array")
  • dictionary pattern

    Works in the same way as the array pattern. Every key has to be a constant pattern.

    The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern doesn’t match.

    Open-ended dictionary: A dictionary can be bigger than the pattern by making the last subpattern ..

    Every subpattern has to be comma separated.

    If you don’t specify a value, then only the existence of the key is checked.

    A value pattern is separated from the key pattern with a :

    1. match x:
    2. {}:
    3. print("Empty dict")
    4. {"name": "Dennis"}:
    5. print("The name is Dennis")
    6. {"name": "Dennis", "age": var age}:
    7. print("Dennis is ", age, " years old.")
    8. {"name", "age"}:
    9. print("Has a name and an age, but it's not Dennis :(")
    10. {"key": "godotisawesome", ..}:
    11. print("I only checked for one entry and ignored the rest")

Multipatterns:

You can also specify multiple patterns separated by a comma. These patterns aren’t allowed to have any bindings in them.

  1. match x:
  2. 1, 2, 3:
  3. print("It's 1 - 3")
  4. "Sword", "Splash potion", "Fist":
  5. print("Yep, you've taken damage")

Classes

By default, all script files are unnamed classes. In this case, you can only reference them using the file’s path, using either a relative or an absolute path. For example, if you name a script file character.gd

  1. # Inherit from Character.gd
  2. extends res://path/to/character.gd
  3. # Load character.gd and create a new node instance from it
  4. var Character = load("res://path/to/character.gd")
  5. var character_node = Character.new()

Instead, you can give your class a name to register it as a new type in Godot’s editor. For that, you use the ‘class_name’ keyword. You can add an optional comma followed by a path to an image, to use it as an icon. Your class will then appear with its new icon in the editor:

  1. # Item.gd
  2. extends Node
  3. class_name Item, "res://interface/icons/item.png"

../../../_images/class_name_editor_register_example.png

Here’s a class file example:

  1. # Saved as a file named 'character.gd'.
  2. class_name Character
  3. var health = 5
  4. func print_health():
  5. print(health)
  6. func print_this_script_three_times():
  7. print(get_script())
  8. print(ResourceLoader.load("res://character.gd"))
  9. print(Character)

Note

Godot’s class syntax is compact: it can only contain member variables or functions. You can use static functions, but not static member variables. In the same way, the engine initializes variables every time you create an instance, and this includes arrays and dictionaries. This is in the spirit of thread safety, since scripts can be initialized in separate threads without the user knowing.

Inheritance

A class (stored as a file) can inherit from

  • A global class
  • Another class file
  • An inner class inside another class file.

Multiple inheritance is not allowed.

Inheritance uses the extends keyword:

  1. # Inherit/extend a globally available class.
  2. extends SomeClass
  3. # Inherit/extend a named class file.
  4. extends "somefile.gd"
  5. # Inherit/extend an inner class in another file.
  6. extends "somefile.gd".SomeInnerClass

To check if a given instance inherits from a given class, the is keyword can be used:

  1. # Cache the enemy class.
  2. const Enemy = preload("enemy.gd")
  3. # [...]
  4. # Use 'is' to check inheritance.
  5. if (entity is Enemy):
  6. entity.apply_damage()

To call a function in a base class (i.e. one extend-ed in your current class), prepend . to the function name:

  1. .basefunc(args)

This is especially useful because functions in extending classes replace functions with the same name in their base classes. So if you still want to call them, you can use . like the super keyword in other languages:

  1. func some_func(x):
  2. .some_func(x) # Calls same function on the parent class.

Class Constructor

The class constructor, called on class instantiation, is named _init. As mentioned earlier, the constructors of parent classes are called automatically when inheriting a class. So there is usually no need to call ._init() explicitly.

Unlike the call of a regular function, like in the above example with .some_func, if the constructor from the inherited class takes arguments, they are passed like this:

  1. func _init(args).(parent_args):
  2. pass

This is better explained through examples. Say we have this scenario:

  1. # State.gd (inherited class)
  2. var entity = null
  3. var message = null
  4. func _init(e=null):
  5. entity = e
  6. func enter(m):
  7. message = m
  8. # Idle.gd (inheriting class)
  9. extends "State.gd"
  10. func _init(e=null, m=null).(e):
  11. # Do something with 'e'.
  12. message = m

There are a few things to keep in mind here:

  1. if the inherited class (State.gd) defines a _init constructor that takes arguments (e in this case), then the inheriting class (Idle.gd) has to define _init as well and pass appropriate parameters to _init from State.gd
  2. Idle.gd can have a different number of arguments than the base class State.gd
  3. in the example above, e passed to the State.gd constructor is the same e passed in to Idle.gd
  4. if Idle.gd’s _init constructor takes 0 arguments, it still needs to pass some value to the State.gd base class even if it does nothing. Which brings us to the fact that you can pass literals in the base constructor as well, not just variables. Eg.:
  1. # Idle.gd
  2. func _init().(5):
  3. pass

Inner classes

A class file can contain inner classes. Inner classes are defined using the class keyword. They are instanced using the ClassName.new() function.

  1. # Inside a class file.
  2. # An inner class in this class file.
  3. class SomeInnerClass:
  4. var a = 5
  5. func print_value_of_a():
  6. print(a)
  7. # This is the constructor of the class file's main class.
  8. func _init():
  9. var c = SomeInnerClass.new()
  10. c.print_value_of_a()

Classes as resources

Classes stored as files are treated as resources. They must be loaded from disk to access them in other classes. This is done using either the load or preload functions (see below). Instancing of a loaded class resource is done by calling the new function on the class object:

  1. # Load the class resource when calling load().
  2. var my_class = load("myclass.gd")
  3. # Preload the class only once at compile time.
  4. const MyClass = preload("myclass.gd")
  5. func _init():
  6. var a = MyClass.new()
  7. a.some_function()

Exports

Class members can be exported. This means their value gets saved along with the resource (e.g. the scene) they’re attached to. They will also be available for editing in the property editor. Exporting is done by using the export keyword:

  1. extends Button
  2. export var number = 5 # Value will be saved and visible in the property editor.

An exported variable must be initialized to a constant expression or have an export hint in the form of an argument to the export keyword (see below).

One of the fundamental benefits of exporting member variables is to have them visible and editable in the editor. This way, artists and game designers can modify values that later influence how the program runs. For this, a special export syntax is provided.

  1. # If the exported value assigns a constant or constant expression,
  2. # the type will be inferred and used in the editor.
  3. export var number = 5
  4. # Export can take a basic data type as an argument, which will be
  5. # used in the editor.
  6. export(int) var number
  7. # Export can also take a resource type to use as a hint.
  8. export(Texture) var character_face
  9. export(PackedScene) var scene_file
  10. # There are many resource types that can be used this way, try e.g.
  11. # the following to list them:
  12. export(Resource) var resource
  13. # Integers and strings hint enumerated values.
  14. # Editor will enumerate as 0, 1 and 2.
  15. export(int, "Warrior", "Magician", "Thief") var character_class
  16. # Editor will enumerate with string names.
  17. export(String, "Rebecca", "Mary", "Leah") var character_name
  18. # Named Enum Values
  19. # Editor will enumerate as THING_1, THING_2, ANOTHER_THING.
  20. enum NamedEnum {THING_1, THING_2, ANOTHER_THING = -1}
  21. export (NamedEnum) var x
  22. # Strings as Paths
  23. # String is a path to a file.
  24. export(String, FILE) var f
  25. # String is a path to a directory.
  26. export(String, DIR) var f
  27. # String is a path to a file, custom filter provided as hint.
  28. export(String, FILE, "*.txt") var f
  29. # Using paths in the global filesystem is also possible,
  30. # but only in tool scripts (see further below).
  31. # String is a path to a PNG file in the global filesystem.
  32. export(String, FILE, GLOBAL, "*.png") var tool_image
  33. # String is a path to a directory in the global filesystem.
  34. export(String, DIR, GLOBAL) var tool_dir
  35. # The MULTILINE setting tells the editor to show a large input
  36. # field for editing over multiple lines.
  37. export(String, MULTILINE) var text
  38. # Limiting editor input ranges
  39. # Allow integer values from 0 to 20.
  40. export(int, 20) var i
  41. # Allow integer values from -10 to 20.
  42. export(int, -10, 20) var j
  43. # Allow floats from -10 to 20, with a step of 0.2.
  44. export(float, -10, 20, 0.2) var k
  45. # Allow values y = exp(x) where y varies between 100 and 1000
  46. # while snapping to steps of 20. The editor will present a
  47. # slider for easily editing the value.
  48. export(float, EXP, 100, 1000, 20) var l
  49. # Floats with Easing Hint
  50. # Display a visual representation of the ease() function
  51. # when editing.
  52. export(float, EASE) var transition_speed
  53. # Colors
  54. # Color given as Red-Green-Blue value
  55. export(Color, RGB) var col # Color is RGB.
  56. # Color given as Red-Green-Blue-Alpha value
  57. export(Color, RGBA) var col # Color is RGBA.
  58. # Another node in the scene can be exported, too.
  59. export(NodePath) var node

It must be noted that even if the script is not being run while at the editor, the exported properties are still editable (see below for “tool”).

Exporting bit flags

Integers used as bit flags can store multiple true/false (boolean) values in one property. By using the export hint int, FLAGS, they can be set from the editor:

  1. # Individually edit the bits of an integer.
  2. export(int, FLAGS) var spell_elements = ELEMENT_WIND | ELEMENT_WATER

Restricting the flags to a certain number of named flags is also possible. The syntax is similar to the enumeration syntax:

  1. # Set any of the given flags from the editor.
  2. export(int, FLAGS, "Fire", "Water", "Earth", "Wind") var spell_elements = 0

In this example, Fire has value 1, Water has value 2, Earth has value 4 and Wind corresponds to value 8. Usually, constants should be defined accordingly (e.g. const ELEMENT_WIND = 8 and so on).

Using bit flags requires some understanding of bitwise operations. If in doubt, boolean variables should be exported instead.

Exporting arrays

Exporting arrays works, but with an important caveat: While regular arrays are created local to every class instance, exported arrays are shared between all instances. This means that editing them in one instance will cause them to change in all other instances. Exported arrays can have initializers, but they must be constant expressions.

  1. # Exported array, shared between all instances.
  2. # Default value must be a constant expression.
  3. export var a = [1, 2, 3]
  4. # Exported arrays can specify type (using the same hints as before).
  5. export(Array, int) var ints = [1,2,3]
  6. export(Array, int, "Red", "Green", "Blue") var enums = [2, 1, 0]
  7. export(Array, Array, float) var two_dimensional = [[1.0, 2.0], [3.0, 4.0]]
  8. # You can omit the default value, but then it would be null if not assigned.
  9. export(Array) var b
  10. export(Array, PackedScene) var scenes
  11. # Typed arrays also work, only initialized empty:
  12. export var vector3s = PoolVector3Array()
  13. export var strings = PoolStringArray()
  14. # Regular array, created local for every instance.
  15. # Default value can include run-time values, but can't
  16. # be exported.
  17. var c = [a, 2, 3]

Setters/getters

It is often useful to know when a class’ member variable changes for whatever reason. It may also be desired to encapsulate its access in some way.

For this, GDScript provides a setter/getter syntax using the setget keyword. It is used directly after a variable definition:

  1. var variable = value setget setterfunc, getterfunc

Whenever the value of variable is modified by an external source (i.e. not from local usage in the class), the setter function (setterfunc above) will be called. This happens before the value is changed. The setter must decide what to do with the new value. Vice versa, when variable is accessed, the getter function (getterfunc above) must return the desired value. Below is an example:

  1. var myvar setget my_var_set, my_var_get
  2. func my_var_set(new_value):
  3. my_var = new_value
  4. func my_var_get():
  5. return my_var # Getter must return a value.

Either of the setter or getter functions can be omitted:

  1. # Only a setter.
  2. var my_var = 5 setget myvar_set
  3. # Only a getter (note the comma).
  4. var my_var = 5 setget ,myvar_get

Get/Setters are especially useful when exporting variables to editor in tool scripts or plugins, for validating input.

As said, local access will not trigger the setter and getter. Here is an illustration of this:

  1. func _init():
  2. # Does not trigger setter/getter.
  3. my_integer = 5
  4. print(my_integer)
  5. # Does trigger setter/getter.
  6. self.my_integer = 5
  7. print(self.my_integer)

Tool mode

Scripts, by default, don’t run inside the editor and only the exported properties can be changed. In some cases, it is desired that they do run inside the editor (as long as they don’t execute game code or manually avoid doing so). For this, the tool keyword exists and must be placed at the top of the file:

  1. tool
  2. extends Button
  3. func _ready():
  4. print("Hello")

Warning

Be cautious when freeing nodes with queue_free() or free() in a tool script (especially the script’s owner itself). As tool scripts run their code in the editor, misusing them may lead to crashing the editor.

Memory management

If a class inherits from Reference, then instances will be freed when no longer in use. No garbage collector exists, just reference counting. By default, all classes that don’t define inheritance extend Reference. If this is not desired, then a class must inherit Object manually and must call instance.free(). To avoid reference cycles that can’t be freed, a weakref function is provided for creating weak references.

Alternatively, when not using references, the is_instance_valid(instance) can be used to check if an object has been freed.

Signals

Signals are a tool to emit messages from an object that other objects can react to. To create custom signals for a class, use the signal keyword.

  1. extends Node
  2. # A signal named health_depleted
  3. signal health_depleted

Note

Signals are a Callback) mechanism. They also fill the role of Observers, a common programming pattern. For more information, read the Observer tutorial in the Game Programming Patterns ebook.

You can connect these signals to methods the same way you connect built-in signals of nodes like Button or RigidBody.

In the example below, we connect the health_depleted signal from a Character node to a Game node. When the Character node emits the signal, the game node’s _on_Character_health_depleted is called:

  1. # Game.gd
  2. func _ready():
  3. var character_node = get_node('Character')
  4. character_node.connect("health_depleted", self, "_on_Character_health_depleted")
  5. func _on_Character_health_depleted():
  6. get_tree().reload_current_scene()

You can emit as many arguments as you want along with a signal.

Here is an example where this is useful. Let’s say we want a life bar on screen to react to health changes with an animation, but we want to keep the user interface separate from the player in our scene tree.

In our Character.gd script, we define a health_changed signal and emit it with Object.emit_signal(), and from a Game node higher up our scene tree, we connect it to the Lifebar using the Object.connect() method:

  1. # Character.gd
  2. ...
  3. signal health_changed
  4. func take_damage(amount):
  5. var old_health = health
  6. health -= amount
  7. # We emit the health_changed signal every time the
  8. # character takes damage
  9. emit_signal("health_changed", old_health, health)
  10. ...
  1. # Lifebar.gd
  2. # Here, we define a function to use as a callback when the
  3. # character's health_changed signal is emitted
  4. ...
  5. func _on_Character_health_changed(old_value, new_value):
  6. if old_value > new_value:
  7. progress_bar.modulate = Color.red
  8. else:
  9. progress_bar.modulate = Color.green
  10. # Imagine that `animate` is a user-defined function that animates the
  11. # bar filling up or emptying itself
  12. progress_bar.animate(old_value, new_value)
  13. ...

Note

To use signals, your class has to extend the Object class or any type extending it like Node, KinematicBody, Control

In the Game node, we get both the Character and Lifebar nodes, then connect the character, that emits the signal, to the receiver, the Lifebar node in this case.

  1. # Game.gd
  2. func _ready():
  3. var character_node = get_node('Character')
  4. var lifebar_node = get_node('UserInterface/Lifebar')
  5. character_node.connect("health_changed", lifebar_node, "_on_Character_health_changed")

This allows the Lifebar to react to health changes without coupling it to the Character node.

you can write optional argument names in parentheses after the signal’s definition.

  1. # Defining a signal that forwards two arguments
  2. signal health_changed(old_value, new_value)

These arguments show up in the editor’s node dock, and Godot can use them to generate callback functions for you. However, you can still emit any number of arguments when you emit signals. So it’s up to you to emit the correct values.

../../../_images/gdscript_basics_signals_node_tab_1.png

GDScript can bind an array of values to connections between a signal and a method. When the signal is emitted, the callback method receives the bound values. These bound arguments are unique to each connection, and the values will stay the same.

You can use this array of values to add extra constant information to the connection if the emitted signal itself doesn’t give you access to all the data that you need.

Building on the example above, let’s say we want to display a log of the damage taken by each character on the screen, like Player1 took 22 damage.. The health_changed signal doesn’t give us the name of the character that took damage. So when we connect the signal to the in-game console, we can add the character’s name in the binds array argument:

  1. # Game.gd
  2. func _ready():
  3. var character_node = get_node('Character')
  4. var battle_log_node = get_node('UserInterface/BattleLog')
  5. character_node.connect("health_changed", battle_log_node, "_on_Character_health_changed", [character_node.name])

Our BattleLog node receives each element in the binds array as an extra argument:

  1. # BattleLog.gd
  2. func _on_Character_health_changed(old_value, new_value, character_name):
  3. if not new_value <= old_value:
  4. return
  5. var damage = old_value - new_value
  6. label.text += character_name + " took " + str(damage) + " damage."

Coroutines with yield

GDScript offers support for coroutines via the yield built-in function. Calling yield() will immediately return from the current function, with the current frozen state of the same function as the return value. Calling resume on this resulting object will continue execution and return whatever the function returns. Once resumed, the state object becomes invalid. Here is an example:

  1. func my_func():
  2. print("Hello")
  3. yield()
  4. print("world")
  5. func _ready():
  6. var y = my_func()
  7. # Function state saved in 'y'.
  8. print("my dear")
  9. y.resume()
  10. # 'y' resumed and is now an invalid state.

Will print:

  1. Hello
  2. my dear
  3. world

It is also possible to pass values between yield() and resume(), for example:

  1. func my_func():
  2. print("Hello")
  3. print(yield())
  4. return "cheers!"
  5. func _ready():
  6. var y = my_func()
  7. # Function state saved in 'y'.
  8. print(y.resume("world"))
  9. # 'y' resumed and is now an invalid state.

Will print:

  1. Hello
  2. world
  3. cheers!

Coroutines & signals

The real strength of using yield is when combined with signals. yield can accept two arguments, an object and a signal. When the signal is received, execution will recommence. Here are some examples:

  1. # Resume execution the next frame.
  2. yield(get_tree(), "idle_frame")
  3. # Resume execution when animation is done playing.
  4. yield(get_node("AnimationPlayer"), "finished")
  5. # Wait 5 seconds, then resume execution.
  6. yield(get_tree().create_timer(5.0), "timeout")

Coroutines themselves use the completed signal when they transition into an invalid state, for example:

  1. func my_func():
  2. yield(button_func(), "completed")
  3. print("All buttons were pressed, hurray!")
  4. func button_func():
  5. yield($Button0, "pressed")
  6. yield($Button1, "pressed")

my_func will only continue execution once both buttons have been pressed.

Onready keyword

When using nodes, it’s common to desire to keep references to parts of the scene in a variable. As scenes are only warranted to be configured when entering the active scene tree, the sub-nodes can only be obtained when a call to Node._ready() is made.

  1. var my_label
  2. func _ready():
  3. my_label = get_node("MyLabel")

This can get a little cumbersome, especially when nodes and external references pile up. For this, GDScript has the onready keyword, that defers initialization of a member variable until _ready is called. It can replace the above code with a single line:

  1. onready var my_label = get_node("MyLabel")

Assert keyword

The assert keyword can be used to check conditions in debug builds. These assertions are ignored in non-debug builds.

  1. # Check that 'i' is 0.
  2. assert(i == 0)