GDScript reference

GDScript is a high-level, object-oriented, imperative, and gradually typed programming language built for Godot. It uses an indentation-based syntax similar to languages like Python. Its goal is to be optimized for and tightly integrated with Godot Engine, allowing great flexibility for content creation and integration.

GDScript is entirely independent from Python and is not based on it.

History

Note

Documentation about GDScript’s history has been moved to the Frequently Asked Questions.

Example of GDScript

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

  1. # Everything after "#" is a comment.
  2. # A file is a class!
  3. # (optional) icon to show in the editor dialogs:
  4. @icon("res://path/to/optional/icon.svg")
  5. # (optional) class definition:
  6. class_name MyClass
  7. # Inheritance:
  8. extends BaseClass
  9. # Member variables.
  10. var a = 5
  11. var s = "Hello"
  12. var arr = [1, 2, 3]
  13. var dict = {"key": "value", 2: 3}
  14. var other_dict = {key = "value", other_key = 2}
  15. var typed_var: int
  16. var inferred_type := "String"
  17. # Constants.
  18. const ANSWER = 42
  19. const THE_NAME = "Charly"
  20. # Enums.
  21. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  22. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  23. # Built-in vector types.
  24. var v2 = Vector2(1, 2)
  25. var v3 = Vector3(1, 2, 3)
  26. # Functions.
  27. func some_function(param1, param2, param3):
  28. const local_const = 5
  29. if param1 < local_const:
  30. print(param1)
  31. elif param2 > 5:
  32. print(param2)
  33. else:
  34. print("Fail!")
  35. for i in range(20):
  36. print(i)
  37. while param2 != 0:
  38. param2 -= 1
  39. match param3:
  40. 3:
  41. print("param3 is 3!")
  42. _:
  43. print("param3 is not 3!")
  44. var local_var = param1 + 3
  45. return local_var
  46. # Functions override functions with the same name on the base/super class.
  47. # If you still want to call them, use "super":
  48. func something(p1, p2):
  49. super(p1, p2)
  50. # It's also possible to call another function in the super class:
  51. func other_something(p1, p2):
  52. super.something(p1, p2)
  53. # Inner class
  54. class Something:
  55. var a = 10
  56. # Constructor
  57. func _init():
  58. print("Constructed!")
  59. var lv = Something.new()
  60. 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).

Identifiers may also contain most Unicode characters part of UAX#31. This allows you to use identifier names written in languages other than English. Unicode characters that are considered “confusable” for ASCII characters and emoji are not allowed in identifiers.

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.

Keyword

Description

if

See if/else/elif.

elif

See if/else/elif.

else

See if/else/elif.

for

See for.

while

See while.

match

See match.

break

Exits the execution of the current for or while loop.

continue

Immediately skips to the next iteration of the for or while loop.

pass

Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions.

return

Returns a value from a function.

class

Defines an inner class. See Inner classes.

class_name

Defines the script as a globally accessible class with the specified name. See Registering named classes.

extends

Defines what class to extend with the current class.

is

Tests whether a variable extends a given class, or is of a given built-in type.

in

Tests whether a value is within a string, array, range, dictionary, or node. When used with for, it iterates through them instead of testing.

as

Cast the value to a given type if possible.

self

Refers to current class instance.

signal

Defines a signal.

func

Defines a function.

static

Defines a static function or a static member variable.

const

Defines a constant.

enum

Defines an enum.

var

Defines a variable.

breakpoint

Editor helper for debugger breakpoints. Unlike breakpoints created by clicking in the gutter, breakpoint is stored in the script itself. This makes it persistent across different machines when using version control.

preload

Preloads a class or variable. See Classes as resources.

await

Waits for a signal or a coroutine to finish. See Awaiting for signals or coroutines.

yield

Previously used for coroutines. Kept as keyword for transition.

assert

Asserts a condition, logs error on failure. Ignored in non-debug builds. See Assert keyword.

void

Used to represent that a function does not return any value.

PI

PI constant.

TAU

TAU constant.

INF

Infinity constant. Used for comparisons and as result of calculations.

NAN

NAN (not a number) constant. Used as impossible result from calculations.

Operators

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

Operator

Description

( )

Grouping (highest priority)

Parentheses are not really an operator, but allow you to explicitly specify the precedence of an operation.

x[index]

Subscription

x.attribute

Attribute reference

foo()

Function call

await x

Awaiting for signals or coroutines

x is Node

Type checking

See also is_instance_of() function.

x y

Power

Multiplies x by itself y times, similar to calling pow() function.

Note: In GDScript, the operator is left-associative. See a detailed note after the table.

~x

Bitwise NOT

+x
-x

Identity / Negation

x y
x / y
x % y

Multiplication / Division / Remainder

The % operator is additionally used for format strings.

Note: These operators have the same behavior as C++, which may be unexpected for users coming from Python, JavaScript, etc. See a detailed note after the table.

x + y
x - y

Addition (or Concatenation) / Subtraction

x << y
x >> y

Bit shifting

x & y

Bitwise AND

x ^ y

Bitwise XOR

x | y

Bitwise OR

x == y
x != y
x < y
x > y
x <= y
x >= y

Comparison

See a detailed note after the table.

x in y
x not in y

Inclusion checking

in is also used with the for keyword as part of the syntax.

not x
!x

Boolean NOT and its unrecommended alias

x and y
x && y

Boolean AND and its unrecommended alias

x or y
x || y

Boolean OR and its unrecommended alias

true_expr if cond else false_expr

Ternary if/else

x as Node

Type casting

x = y
x += y
x -= y
x = y
x /= y
x **= y
x %= y
x &= y
x |= y
x ^= y
x <<= y
x >>= y

Assignment (lowest priority)

You cannot use an assignment operator inside an expression.

Note

The behavior of some operators may differ from what you expect:

  1. If both operands of the / operator are int, then integer division is performed instead of fractional. For example 5 / 2 == 2, not 2.5. If this is not desired, use at least one float literal (x / 2.0), cast (float(x) / y), or multiply by 1.0 (x * 1.0 / y).

  2. The % operator is only available for ints, for floats use the fmod() function.

  3. For negative values, the % operator and fmod() use truncation instead of rounding towards negative infinity. This means that the remainder has a sign. If you need the remainder in a mathematical sense, use the posmod() and fposmod() functions instead.

  4. The ** operator is left-associative. This means that 2 ** 2 ** 3 is equal to (2 ** 2) ** 3. Use parentheses to explicitly specify precedence you need, for example 2 ** (2 ** 3).

  5. The == and != operators sometimes allow you to compare values of different types (for example, 1 == 1.0 is true), but in other cases it can cause a runtime error. If you’re not sure about the types of the operands, you can safely use the is_same() function (but note that it is more strict about types and references). To compare floats, use the is_equal_approx() and is_zero_approx() functions instead.

Literals

Example(s)

Description

null

Null value

false, true

Boolean values

45

Base 10 integer

0x8f51

Base 16 (hexadecimal) integer

0b101010

Base 2 (binary) integer

3.14, 58.1e-10

Floating-point number (real)

“Hello”, ‘Hi’

Regular strings

“””Hello”””, ‘’’Hi’’’

Triple-quoted regular strings

r”Hello”, r’Hi’

Raw strings

r”””Hello”””, r’’’Hi’’’

Triple-quoted raw strings

&”name”

StringName

^”Node/Label”

NodePath

There are also two constructs that look like literals, but actually are not:

Example

Description

$NodePath

Shorthand for get_node(“NodePath”)

%UniqueNode

Shorthand for get_node(“%UniqueNode”)

Integers and floats can have their numbers separated with _ to make them more readable. The following ways to write numbers are all valid:

  1. 12_345_678 # Equal to 12345678.
  2. 3.141_592_7 # Equal to 3.1415927.
  3. 0x8080_0000_ffff # Equal to 0x80800000ffff.
  4. 0b11_00_11_00 # Equal to 0b11001100.

Regular string literals can contain the following escape sequences:

Escape sequence

Expands to

\n

Newline (line feed)

\t

Horizontal tab character

\r

Carriage return

\a

Alert (beep/bell)

\b

Backspace

\f

Formfeed page break

\v

Vertical tab character

\”

Double quote

\’

Single quote

\

Backslash

\uXXXX

UTF-16 Unicode codepoint XXXX (hexadecimal, case-insensitive)

\UXXXXXX

UTF-32 Unicode codepoint XXXXXX (hexadecimal, case-insensitive)

There are two ways to represent an escaped Unicode character above 0xFFFF:

Also, using \ followed by a newline inside a string will allow you to continue it in the next line, without inserting a newline character in the string itself.

A string enclosed in quotes of one type (for example ") can contain quotes of another type (for example ') without escaping. Triple-quoted strings allow you to avoid escaping up to two consecutive quotes of the same type (unless they are adjacent to the string edges).

Raw string literals always encode the string as it appears in the source code. This is especially useful for regular expressions. Raw strings do not process escape sequences, but you can “escape” a quote or backslash (they replace themselves).

  1. print("\tchar=\"\\t\"") # Prints ` char="\t"`.
  2. print(r"\tchar=\"\\t\"") # Prints `\tchar=\"\\t\"`.

GDScript also supports format strings.

Annotations

There are some special tokens in GDScript that act like keywords but are not, they are annotations instead. Every annotation start with the @ character and is specified by a name. A detailed description and example for each annotation can be found inside the GDScript class reference.

Annotations affect how the script is treated by external tools and usually don’t change the behavior.

For instance, you can use it to export a value to the editor:

  1. @export_range(1, 100, 1, "or_greater")
  2. var ranged_var: int = 50

For more information about exporting properties, read the GDScript exports article.

Any constant expression compatible with the required argument type can be passed as an annotation argument value:

  1. const MAX_SPEED = 120.0
  2. @export_range(0.0, 0.5 * MAX_SPEED)
  3. var initial_speed: float = 0.25 * MAX_SPEED

Annotations can be specified one per line or all in the same line. They affect the next statement that isn’t an annotation. Annotations can have arguments sent between parentheses and separated by commas.

Both of these are the same:

  1. @annotation_a
  2. @annotation_b
  3. var variable
  4. @annotation_a @annotation_b var variable

@onready annotation

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 annotation, 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")

Warning

Applying @onready and any @export annotation to the same variable doesn’t work as you might expect. The @onready annotation will cause the default value to be set after the @export takes effect and will override it:

  1. @export var a = "init_value_a"
  2. @onready @export var b = "init_value_b"
  3. func _init():
  4. prints(a, b) # init_value_a <null>
  5. func _notification(what):
  6. if what == NOTIFICATION_SCENE_INSTANTIATED:
  7. prints(a, b) # exported_value_a exported_value_b
  8. func _ready():
  9. prints(a, b) # exported_value_a init_value_b

Therefore, the ONREADY_WITH_EXPORT warning is generated, which is treated as an error by default. We do not recommend disabling or ignoring it.

Comments

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

  1. # This is a comment.

Tip

In the Godot script editor, special keywords are highlighted within comments to bring the user’s attention to specific comments:

  • Critical (appears in red): ALERT, ATTENTION, CAUTION, CRITICAL, DANGER, SECURITY

  • Warning (appears in yellow): BUG, DEPRECATED, FIXME, HACK, TASK, TBD, TODO, WARNING

  • Notice (appears in green): INFO, NOTE, NOTICE, TEST, TESTING

These keywords are case-sensitive, so they must be written in uppercase for them to be recognized:

  1. # In the example below, "TODO" will appear in yellow by default.
  2. # The `:` symbol after the keyword is not required, but it's often used.
  3. # TODO: Add more items for the player to choose from.

The list of highlighted keywords and their colors can be changed in the Text Editor > Theme > Comment Markers section of the Editor Settings.

Code regions

Code regions are special types of comments that the script editor understands as foldable regions. This means that after writing code region comments, you can collapse and expand the region by clicking the arrow that appears at the left of the comment. This arrow appears within a purple square to be distinguishable from standard code folding.

The syntax is as follows:

  1. # Important: There must be *no* space between the `#` and `region` or `endregion`.
  2. # Region without a description:
  3. #region
  4. ...
  5. #endregion
  6. # Region with a description:
  7. #region Some description that is displayed even when collapsed
  8. ...
  9. #endregion

Tip

To create a code region quickly, select several lines in the script editor, right-click the selection then choose Create Code Region. The region description will be selected automatically for editing.

It is possible to nest code regions within other code regions.

Here’s a concrete usage example of code regions:

  1. # This comment is outside the code region. It will be visible when collapsed.
  2. #region Terrain generation
  3. # This comment is inside the code region. It won't be visible when collapsed.
  4. func generate_lakes():
  5. pass
  6. func generate_hills():
  7. pass
  8. #endregion
  9. #region Terrain population
  10. func place_vegetation():
  11. pass
  12. func place_roads():
  13. pass
  14. #endregion

This can be useful to organize large chunks of code into easier to understand sections. However, remember that external editors generally don’t support this feature, so make sure your code is easy to follow even when not relying on folding code regions.

Note

Individual functions and indented sections (such as if and for) can always be collapsed in the script editor. This means you should avoid using a code region to contain a single function or indented section, as it won’t bring much of a benefit. Code regions work best when they’re used to group multiple elements together.

Line continuation

A line of code in GDScript can be continued on the next line by using a backslash (\). Add one at the end of a line and the code on the next line will act like it’s where the backslash is. Here is an example:

  1. var a = 1 + \
  2. 2

A line can be continued multiple times like this:

  1. var a = 1 + \
  2. 4 + \
  3. 10 + \
  4. 4

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 exceptions are Object, Array, Dictionary, and packed arrays (such as PackedByteArray), which are passed by reference so they are shared. All arrays, Dictionary, and some objects (Node, Resource) have a duplicate() method that allows you to make a copy.

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

Short for “boolean”, it can only contain true or false.

int

Short for “integer”, it stores whole numbers (positive and negative). It is stored as a 64-bit value, equivalent to int64_t in C++.

float

Stores real numbers, including decimals, using floating-point values. It is stored as a 64-bit value, equivalent to double in C++. Note: Currently, data structures such as Vector2, Vector3, and PackedFloat32Array store 32-bit single-precision float values.

String

A sequence of characters in Unicode format.

StringName

An immutable string that allows only one instance of each name. They are slower to create and may result in waiting for locks when multithreading. In exchange, they’re very fast to compare, which makes them good candidates for dictionary keys.

NodePath

A pre-parsed path to a node or a node property. It can be easily assigned to, and from, a String. They are useful to interact with the tree to get a node, or affecting properties like with Tweens.

Vector built-in types

Vector2

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

Vector2i

Same as a Vector2 but the components are integers. Useful for representing items in a 2D grid.

Rect2

2D Rectangle type containing two vectors fields: position and size. Also 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.

Vector3i

Same as Vector3 but the components are integers. Can be use for indexing items in a 3D grid.

Transform2D

3×2 matrix used for 2D transforms.

Plane

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

Quaternion

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. Also 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.

Transform3D

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.

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. Negative indices 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].

Typed arrays

Godot 4.0 added support for typed arrays. On write operations, Godot checks that element values match the specified type, so the array cannot contain invalid values. The GDScript static analyzer takes typed arrays into account, however array methods like front() and back() still have the Variant return type.

Typed arrays have the syntax Array[Type], where Type can be any Variant type, native or user class, or enum. Nested array types (like Array[Array[int]]) are not supported.

  1. var a: Array[int]
  2. var b: Array[Node]
  3. var c: Array[MyClass]
  4. var d: Array[MyEnum]
  5. var e: Array[Variant]

Array and Array[Variant] are the same thing.

Note

Arrays are passed by reference, so the array element type is also an attribute of the in-memory structure referenced by a variable in runtime. The static type of a variable restricts the structures that it can reference to. Therefore, you cannot assign an array with a different element type, even if the type is a subtype of the required type.

If you want to convert a typed array, you can create a new array and use the Array.assign() method:

  1. var a: Array[Node2D] = [Node2D.new()]
  2. # (OK) You can add the value to the array because `Node2D` extends `Node`.
  3. var b: Array[Node] = [a[0]]
  4. # (Error) You cannot assign an `Array[Node2D]` to an `Array[Node]` variable.
  5. b = a
  6. # (OK) But you can use the `assign()` method instead. Unlike the `=` operator,
  7. # the `assign()` method copies the contents of the array, not the reference.
  8. b.assign(a)

The only exception was made for the Array (Array[Variant]) type, for user convenience and compatibility with old code. However, operations on untyped arrays are considered unsafe.

Packed arrays

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 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). However, keys written in this form can’t start with a digit (like any GDScript identifier), and must be string literals.

  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.
  5. var test = 4
  6. # Prints "hello" by indexing the dictionary with a dynamic key.
  7. # This is not the same as `d.test`. The bracket syntax equivalent to
  8. # `d.test` is `d["test"]`.
  9. print(d[test])

Note

The bracket syntax can be used to access properties of any Object, not just Dictionaries. Keep in mind it will cause a script error when attempting to index a non-existing property. To avoid this, use the Object.get() and Object.set() methods instead.

Signal

A signal is a message that can be emitted by an object to those who want to listen to it. The Signal type can be used for passing the emitter around.

Signals are better used by getting them from actual objects, e.g. $Button.button_up.

Callable

Contains an object and a function, which is useful for passing functions as values (e.g. when connecting to signals).

Getting a method as a member returns a callable. var x = $Sprite2D.rotate will set the value of x to a callable with $Sprite2D as the object and rotate as the method.

You can call it using the call method: x.call(PI).

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 = Sprite2D.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 := Sprite2D.new() # 'my_node' is of type 'Sprite2D'.

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.

  • Autoloads registered as singletons.

Note

While Variant is a valid type specification, it’s not an actual type. It only means there’s no set type and is equivalent to not having a static type at all. Therefore, inference is not allowed by default for Variant, since it’s likely a mistake.

You can turn off this check, or make it only a warning, by changing it in the project settings. See GDScript warning system for details.

Static variables

A class member variable can be declared static:

  1. static var a

Static variables belong to the class, not instances. This means that static variables share values between multiple instances, unlike regular member variables.

From inside a class, you can access static variables from any function, both static and non-static. From outside the class, you can access static variables using the class or an instance (the second is not recommended as it is less readable).

Note

The @export and @onready annotations cannot be applied to a static variable. Local variables cannot be static.

The following example defines a Person class with a static variable named max_id. We increment the max_id in the _init() function. This makes it easy to keep track of the number of Person instances in our game.

  1. # person.gd
  2. class_name Person
  3. static var max_id = 0
  4. var id
  5. var name
  6. func _init(p_name):
  7. max_id += 1
  8. id = max_id
  9. name = p_name

In this code, we create two instances of our Person class and check that the class and every instance have the same max_id value, because the variable is static and accessible to every instance.

  1. # test.gd
  2. extends Node
  3. func _ready():
  4. var person1 = Person.new("John Doe")
  5. var person2 = Person.new("Jane Doe")
  6. print(person1.id) # 1
  7. print(person2.id) # 2
  8. print(Person.max_id) # 2
  9. print(person1.max_id) # 2
  10. print(person2.max_id) # 2

Static variables can have type hints, setters and getters:

  1. static var balance: int = 0
  2. static var debt: int:
  3. get:
  4. return -balance
  5. set(value):
  6. balance = -value

A base class static variable can also be accessed via a child class:

  1. class A:
  2. static var x = 1
  3. class B extends A:
  4. pass
  5. func _ready():
  6. prints(A.x, B.x) # 1 1
  7. A.x = 2
  8. prints(A.x, B.x) # 2 2
  9. B.x = 3
  10. prints(A.x, B.x) # 3 3

@static_unload annotation

Since GDScript classes are resources, having static variables in a script prevents it from being unloaded even if there are no more instances of that class and no other references left. This can be important if static variables store large amounts of data or hold references to other project resources, such as scenes. You should clean up this data manually, or use the @static_unload annotation if static variables don’t store important data and can be reset.

Warning

Currently, due to a bug, scripts are never freed, even if @static_unload annotation is used.

Note that @static_unload applies to the entire script (including inner classes) and must be placed at the top of the script, before class_name and extends:

  1. @static_unload
  2. class_name MyNode
  3. extends Node

See also Static functions and Static constructor.

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 = $Sprite2D as Node2D # Works since Sprite2D 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 as Node2D # 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 the scene tree:

  1. # Will infer the variable to be of type Sprite2D.
  2. var my_sprite := $Character as Sprite2D
  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 values you cannot change when the game is running. Their value must be known at compile-time. Using the const keyword allows you to give a constant value a name. Trying to assign a value to a constant after it’s declared will give you an error.

We recommend using constants whenever a value is not meant to change.

  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 (`A` is a constant).

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.

You can also create constants inside a function, which is useful to name local magic values.

Note

Since objects, arrays and dictionaries are passed by reference, constants are “flat”. This means that if you declare a constant array or dictionary, it can still be modified afterwards. They can’t be reassigned with another value though.

Enums

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

  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

If you pass a name to the enum, it will put all the keys inside a constant Dictionary of that name. This means all constant methods of a dictionary can also be used with a named enum.

Important

Keys in a named enum are not registered as global constants. They should be accessed prefixed by the enum’s name (Name.KEY).

  1. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  2. # Is the same as:
  3. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  4. func _ready():
  5. # Access values with Name.KEY, prints '5'
  6. print(State.STATE_JUMP)
  7. # Use constant dictionary functions
  8. # prints '["STATE_IDLE", "STATE_JUMP", "STATE_SHOOT"]'
  9. print(State.keys())

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.

If a function contains only one line of code, it can be written on one line:

  1. func square(a): return a * a
  2. func hello_world(): print("Hello World")
  3. func empty_function(): pass

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. func 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

Functions are first-class items in terms of the Callable object. Referencing a function by name without calling it will automatically generate the proper callable. This can be used to pass functions as arguments.

  1. func map(arr: Array, function: Callable) -> Array:
  2. var result = []
  3. for item in arr:
  4. result.push_back(function.call(item))
  5. return result
  6. func add1(value: int) -> int:
  7. return value + 1;
  8. func _ready() -> void:
  9. var my_array = [1, 2, 3]
  10. var plus_one = map(my_array, add1)
  11. print(plus_one) # Prints [2, 3, 4].

Note

Callables must be called with the call method. You cannot use the () operator directly. This behavior is implemented to avoid performance issues on direct function calls.

Lambda functions

Lambda functions allow you to declare functions that do not belong to a class. Instead a Callable object is created and assigned to a variable directly. This can be useful to create Callables to pass around without polluting the class scope.

  1. var lambda = func(x): print(x)
  2. lambda.call(42) # Prints "42"

Lambda functions can be named for debugging purposes:

  1. var lambda = func my_lambda(x):
  2. print(x)

Lambda functions capture the local environment. Local variables are passed by value, so they won’t be updated in the lambda if changed in the local function:

  1. var x = 42
  2. var my_lambda = func(): print(x)
  3. my_lambda.call() # Prints "42"
  4. x = "Hello"
  5. my_lambda.call() # Prints "42"

Note

The values of the outer scope behave like constants. Therefore, if you declare an array or dictionary, it can still be modified afterwards.

Static functions

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

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

Lambdas cannot be declared static.

See also Static variables and Static constructor.

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.

Expressions

Expressions are sequences of operators and their operands in orderly fashion. An expression by itself can be a statement too, though only calls are reasonable to use as statements since other expressions don’t have side effects.

Expressions return values that can be assigned to valid targets. Operands to some operator can be another expression. An assignment is not an expression and thus does not return any value.

Here are some examples of expressions:

  1. 2 + 2 # Binary operation.
  2. -5 # Unary operation.
  3. "okay" if x > 4 else "not okay" # Ternary operation.
  4. x # Identifier representing variable or constant.
  5. x.a # Attribute access.
  6. x[4] # Subscript access.
  7. x > 2 or x < 5 # Comparisons and logic operators.
  8. x == y + 2 # Equality test.
  9. do_something() # Function call.
  10. [1, 2, 3] # Array definition.
  11. {A = 1, B = 2} # Dictionary definition.
  12. preload("res://icon.png") # Preload builtin function.
  13. self # Reference to current instance.

Identifiers, attributes, and subscripts are valid assignment targets. Other expressions cannot be on the left side of an assignment.

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

Ternary-if expressions can be nested to handle more than 2 cases. When nesting ternary-if expressions, it is recommended to wrap the complete expression over multiple lines to preserve readability:

  1. var count = 0
  2. var fruit = (
  3. "apple" if count == 2
  4. else "pear" if count == 1
  5. else "banana" if count == 0
  6. else "orange"
  7. )
  8. print(fruit) # banana
  9. # Alternative syntax with backslashes instead of parentheses (for multi-line expressions).
  10. # Less lines required, but harder to refactor.
  11. var fruit_alt = \
  12. "apple" if count == 2 \
  13. else "pear" if count == 1 \
  14. else "banana" if count == 0 \
  15. else "orange"
  16. print(fruit_alt) # banana

You may also wish to check if a value is contained within something. You can use an if statement combined with the in operator to accomplish this:

  1. # Check if a letter is in a string.
  2. var text = "abc"
  3. if 'b' in text: print("The string contains b")
  4. # Check if a variable is contained within a node.
  5. if "varName" in get_parent(): print("varName is defined in parent!")

while

Simple loops are created by using while syntax. Loops can be broken using break or continued using continue (which skips to the next iteration of the loop without executing any further code in the current iteration):

  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 key 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]) # Prints 0, then 1, then 2.
  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 i in range(8, 2, -2):
  13. statement # Similar to [8, 6, 4] but does not allocate an array.
  14. for c in "Hello":
  15. print(c) # Iterate through all characters in a String, print every letter on new line.
  16. for i in 3:
  17. statement # Similar to range(3).
  18. for i in 2.2:
  19. statement # Similar to range(ceil(2.2)).

If you want to assign values on an array as it is being iterated through, it is best to use for i in array.size().

  1. for i in array.size():
  2. array[i] = "Hello World"

The loop variable is local to the for-loop and assigning to it will not change the value on the array. Objects passed by reference (such as nodes) can still be manipulated by calling methods on the loop variable.

  1. for string in string_array:
  2. string = "Hello World" # This has no effect
  3. for node in node_array:
  4. node.add_to_group("Cool_Group") # This has an effect

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.

Warning

match is more type strict than the == operator. For example 1 will not match 1.0. The only exception is String vs StringName matching: for example, the String "hello" is considered equal to the StringName &"hello".

Basic syntax
  1. match <expression>:
  2. <pattern(s)>:
  3. <block>
  4. <pattern(s)> when <guard expression>:
  5. <block>
  6. <...>
Crash-course for people who are familiar with switch statements
  1. Replace switch with match.

  2. Remove case.

  3. Remove any breaks.

  4. Change default to a single underscore.

Control flow

The patterns are matched from top to bottom. If a pattern matches, the first corresponding block will be executed. After that, the execution continues below the match statement.

Note

The special continue behavior in match supported in 3.x was removed in Godot 4.0.

The following pattern types are available:

  • Literal pattern

    Matches a literal:

    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!")
  • Expression pattern

    Matches a constant expression, an identifier, or an attribute access (A.B):

    1. match typeof(x):
    2. TYPE_FLOAT:
    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 to be honest.")
  • 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")
  • Multiple patterns

    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")
Pattern guards

Only one branch can be executed per match. Once a branch is chosen, the rest are not checked. If you want to use the same pattern for multiple branches or to prevent choosing a branch with too general pattern, you can specify a guard expression after the list of patterns with the when keyword:

  1. match point:
  2. [0, 0]:
  3. print("Origin")
  4. [_, 0]:
  5. print("Point on X-axis")
  6. [0, _]:
  7. print("Point on Y-axis")
  8. [var x, var y] when y == x:
  9. print("Point on line y = x")
  10. [var x, var y] when y == -x:
  11. print("Point on line y = -x")
  12. [var x, var y]:
  13. print("Point (%s, %s)" % [x, y])
  • If there is no matching pattern for the current branch, the guard expression is not evaluated and the patterns of the next branch are checked.

  • If a matching pattern is found, the guard expression is evaluated.

    • If it’s true, then the body of the branch is executed and match ends.

    • If it’s false, then the patterns of the next branch are checked.

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()

Registering named classes

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 optionally use the @icon annotation with 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. @icon("res://interface/icons/item.png")
  3. class_name Item
  4. extends Node

../../../_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)

If you want to use extends too, you can keep both on the same line:

  1. class_name MyNode extends Node

Note

Godot initializes non-static 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

Note

If inheritance is not explicitly defined, the class will default to inheriting RefCounted.

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 super class (i.e. one extend-ed in your current class), use the super keyword:

  1. super(args)

This is especially useful because functions in extending classes replace functions with the same name in their super classes. If you still want to call them, you can use super:

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

If you need to call a different function from the super class, you can specify the function name with the attribute operator:

  1. func overriding():
  2. return 0 # This overrides the method in the base class.
  3. func dont_override():
  4. return super.overriding() # This calls the method as defined in the base class.

Warning

One of the common misconceptions is trying to override non-virtual engine methods such as get_class(), queue_free(), etc. This is not supported for technical reasons.

In Godot 3, you can shadow engine methods in GDScript, and it will work if you call this method in GDScript. However, the engine will not execute your code if the method is called inside the engine on some event.

In Godot 4, even shadowing may not always work, as GDScript optimizes native method calls. Therefore, we added the NATIVE_METHOD_OVERRIDE warning, which is treated as an error by default. We strongly advise against disabling or ignoring the warning.

Note that this does not apply to virtual methods such as _ready(), _process() and others (marked with the virtual qualifier in the documentation and the names start with an underscore). These methods are specifically for customizing engine behavior and can be overridden in GDScript. Signals and notifications can also be useful for these purposes.

Class constructor

The class constructor, called on class instantiation, is named _init. If you want to call the base class constructor, you can also use the super syntax. Note that every class has an implicit constructor that it’s always called (defining the default values of class variables). super is used to call the explicit constructor:

  1. func _init(arg):
  2. super("some_default", arg) # Call the custom base constructor.

This is better explained through examples. Consider 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):
  11. super(e)
  12. # Do something with 'e'.
  13. 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) must 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. This brings us to the fact that you can pass expressions to the base constructor as well, not just variables, e.g.:

    1. # idle.gd
    2. func _init():
    3. super(5)

Static constructor

A static constructor is a static function _static_init that is called automatically when the class is loaded, after the static variables have been initialized:

  1. static var my_static_var = 1
  2. static func _static_init():
  3. my_static_var = 2

A static constructor cannot take arguments and must not return any value.

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 MyClass = 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

Note

Documentation about exports has been moved to GDScript exported properties.

Properties (setters and getters)

Sometimes, you want a class’ member variable to do more than just hold data and actually perform some validation or computation whenever its value changes. It may also be desired to encapsulate its access in some way.

For this, GDScript provides a special syntax to define properties using the set and get keywords after a variable declaration. Then you can define a code block that will be executed when the variable is accessed or assigned.

Example:

  1. var milliseconds: int = 0
  2. var seconds: int:
  3. get:
  4. return milliseconds / 1000
  5. set(value):
  6. milliseconds = value * 1000

Note

Unlike setget in previous Godot versions, the properties setter and getter are always called (except as noted below), even when accessed inside the same class (with or without prefixing with self.). This makes the behavior consistent. If you need direct access to the value, use another variable for direct access and make the property code use that name.

Alternative syntax

Also there is another notation to use existing class functions if you want to split the code from the variable declaration or you need to reuse the code across multiple properties (but you can’t distinguish which property the setter/getter is being called for):

  1. var my_prop:
  2. get = get_my_prop, set = set_my_prop

This can also be done in the same line:

  1. var my_prop: get = get_my_prop, set = set_my_prop

The setter and getter must use the same notation, mixing styles for the same variable is not allowed.

Note

You cannot specify type hints for inline setters and getters. This is done on purpose to reduce the boilerplate. If the variable is typed, then the setter’s argument is automatically of the same type, and the getter’s return value must match it. Separated setter/getter functions can have type hints, and the type must match the variable’s type or be a wider type.

When setter/getter is not called

When a variable is initialized, the value of the initializer will be written directly to the variable. Including if the @onready annotation is applied to the variable.

Using the variable’s name to set it inside its own setter or to get it inside its own getter will directly access the underlying member, so it won’t generate infinite recursion and saves you from explicitly declaring another variable:

  1. signal changed(new_value)
  2. var warns_when_changed = "some value":
  3. get:
  4. return warns_when_changed
  5. set(value):
  6. changed.emit(value)
  7. warns_when_changed = value

This also applies to the alternative syntax:

  1. var my_prop: set = set_my_prop
  2. func set_my_prop(value):
  3. my_prop = value # No infinite recursion.

Warning

The exception does not propagate to other functions called in the setter/getter. For example, the following code will cause an infinite recursion:

  1. var my_prop:
  2. set(value):
  3. set_my_prop(value)
  4. func set_my_prop(value):
  5. my_prop = value # Infinite recursion, since `set_my_prop()` is not the setter.

Tool mode

By default, scripts 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 annotation exists and must be placed at the top of the file:

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

See Running code in the editor for more information.

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

Godot implements reference counting to free certain instances that are no longer used, instead of a garbage collector, or requiring purely manual management. Any instance of the RefCounted class (or any class that inherits it, such as Resource) will be freed automatically when no longer in use. For an instance of any class that is not a RefCounted (such as Node or the base Object type), it will remain in memory until it is deleted with free() (or queue_free() for Nodes).

Note

If a Node is deleted via free() or queue_free(), all of its children will also recursively be deleted.

To avoid reference cycles that can’t be freed, a WeakRef function is provided for creating weak references, which allow access to the object without preventing a RefCounted from freeing. Here is an example:

  1. extends Node
  2. var my_file_ref
  3. func _ready():
  4. var f = FileAccess.open("user://example_file.json", FileAccess.READ)
  5. my_file_ref = weakref(f)
  6. # the FileAccess class inherits RefCounted, so it will be freed when not in use
  7. # the WeakRef will not prevent f from being freed when other_node is finished
  8. other_node.use_file(f)
  9. func _this_is_called_later():
  10. var my_file = my_file_ref.get_ref()
  11. if my_file:
  12. my_file.close()

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 RigidBody3D.

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.health_depleted.connect(_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 Signal.emit(), and from a Game node higher up our scene tree, we connect it to the Lifebar using the Signal.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. health_changed.emit(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. ...

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.health_changed.connect(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; 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.health_changed.connect(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. # battle_log.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."

Awaiting for signals or coroutines

The await keyword can be used to create coroutines which wait until a signal is emitted before continuing execution. Using the await keyword with a signal or a call to a function that is also a coroutine will immediately return the control to the caller. When the signal is emitted (or the called coroutine finishes), it will resume execution from the point on where it stopped.

For example, to stop execution until the user presses a button, you can do something like this:

  1. func wait_confirmation():
  2. print("Prompting user")
  3. await $Button.button_up # Waits for the button_up signal from Button node.
  4. print("User confirmed")
  5. return true

In this case, the wait_confirmation becomes a coroutine, which means that the caller also needs to await for it:

  1. func request_confirmation():
  2. print("Will ask the user")
  3. var confirmed = await wait_confirmation()
  4. if confirmed:
  5. print("User confirmed")
  6. else:
  7. print("User cancelled")

Note that requesting a coroutine’s return value without await will trigger an error:

  1. func wrong():
  2. var confirmed = wait_confirmation() # Will give an error.

However, if you don’t depend on the result, you can just call it asynchronously, which won’t stop execution and won’t make the current function a coroutine:

  1. func okay():
  2. wait_confirmation()
  3. print("This will be printed immediately, before the user press the button.")

If you use await with an expression that isn’t a signal nor a coroutine, the value will be returned immediately and the function won’t give the control back to the caller:

  1. func no_wait():
  2. var x = await get_five()
  3. print("This doesn't make this function a coroutine.")
  4. func get_five():
  5. return 5

This also means that returning a signal from a function that isn’t a coroutine will make the caller await on that signal:

  1. func get_signal():
  2. return $Button.button_up
  3. func wait_button():
  4. await get_signal()
  5. print("Button was pressed")

Note

Unlike yield in previous Godot versions, you cannot obtain the function state object. This is done to ensure type safety. With this type safety in place, a function cannot say that it returns an int while it actually returns a function state object during runtime.

Assert keyword

The assert keyword can be used to check conditions in debug builds. These assertions are ignored in non-debug builds. This means that the expression passed as argument won’t be evaluated in a project exported in release mode. Due to this, assertions must not contain expressions that have side effects. Otherwise, the behavior of the script would vary depending on whether the project is run in a debug build.

  1. # Check that 'i' is 0. If 'i' is not 0, an assertion error will occur.
  2. assert(i == 0)

When running a project from the editor, the project will be paused if an assertion error occurs.

You can optionally pass a custom error message to be shown if the assertion fails:

  1. assert(enemy_power < 256, "Enemy is too powerful!")

Previous Next


© Copyright 2014-present Juan Linietsky, Ariel Manzur and the Godot community (CC BY 3.0). Revision 53e837c6.

Built with Sphinx using a theme provided by Read the Docs.