GDScript reference
GDScript is a high-level,object-oriented,imperative, andgradually typed programming language built for Godot.It uses an indentation-based syntax similar to languages likePython.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 theFrequently Asked Questions.
Example of GDScript
Some people can learn better by taking a look at the syntax, sohere's an example of how GDScript looks.
# Everything after "#" is a comment.# A file is a class!# (optional) icon to show in the editor dialogs:@icon("res://path/to/optional/icon.svg")# (optional) class definition:class_nameMyClass# Inheritance:extendsBaseClass# Member variables.vara=5vars="Hello"vararr=[1,2,3]vardict={"key":"value",2:3}varother_dict={key="value",other_key=2}vartyped_var:intvarinferred_type:="String"# Constants.constANSWER=42constTHE_NAME="Charly"# Enums.enum{UNIT_NEUTRAL,UNIT_ENEMY,UNIT_ALLY}enumNamed{THING_1,THING_2,ANOTHER_THING=-1}# Built-in vector types.varv2=Vector2(1,2)varv3=Vector3(1,2,3)# Functions.funcsome_function(param1,param2,param3):constlocal_const=5ifparam1<local_const:print(param1)elifparam2>5:print(param2)else:print("Fail!")foriinrange(20):print(i)whileparam2!=0:param2-=1matchparam3:3:print("param3 is 3!")_:print("param3 is not 3!")varlocal_var=param1+3returnlocal_var# Functions override functions with the same name on the base/super class.# If you still want to call them, use "super":funcsomething(p1,p2):super(p1,p2)# It's also possible to call another function in the super class:funcother_something(p1,p2):super.something(p1,p2)# Inner classclassSomething:vara=10# Constructorfunc_init():print("Constructed!")varlv=Something.new()print(lv.a)
If you have previous experience with statically typed languages such asC, C++, or C# but never used a dynamically typed one before, it is advised youread this tutorial:GDScript: An introduction to dynamic languages.
Identifiers
Any string that restricts itself to alphabetic characters (a
toz
andA
toZ
), digits (0
to9
) and_
qualifies as an identifier.Additionally, identifiers must not begin with a digit. Identifiers arecase-sensitive (foo
is different fromFOO
).
Identifiers may also contain most Unicode characters part ofUAX#31. This allows you to useidentifier names written in languages other than English. Unicode charactersthat are considered "confusable" for ASCII characters and emoji are not allowedin identifiers.
Keywords
The following is the list of keywords supported by the language. Sincekeywords are reserved words (tokens), they can't be used as identifiers.Operators (likein
,not
,and
oror
) and names of built-in typesas listed in the following sections are also reserved.
Keywords are defined in theGDScript tokenizerin case you want to take a look under the hood.
Keyword | Description |
---|---|
if | Seeif/else/elif. |
elif | Seeif/else/elif. |
else | Seeif/else/elif. |
for | Seefor. |
while | Seewhile. |
match | Seematch. |
when | Used bypattern guards in |
break | Exits the execution of the current |
continue | Immediately skips to the next iteration of the |
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. SeeInner classes. |
class_name | Defines the script as a globally accessible class with the specified name. SeeRegistering 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 |
as | Cast the value to a given type if possible. |
self | Refers to current class instance. Seeself. |
super | Resolves the scope of the parent method. SeeInheritance. |
signal | Defines a signal. SeeSignals. |
func | Defines a function. SeeFunctions. |
static | Defines a static function or a static member variable. |
const | Defines a constant. SeeConstants. |
enum | Defines an enum. SeeEnums. |
var | Defines a variable. SeeVariables. |
breakpoint | Editor helper for debugger breakpoints. Unlike breakpoints created by clicking in the gutter, |
preload | Preloads a class or variable. SeeClasses as resources. |
await | Waits for a signal or a coroutine to finish. SeeAwaiting 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. SeeAssert 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. All binary operators areleft-associative,including the**
operator. This means that2**2**3
is equal to(2**2)**3
. Use parentheses to explicitly specify precedence you need, forexample2**(2**3)
. The ternaryif/else
operator is right-associative.
Operator | Description |
---|---|
| Grouping (highest priority) Parentheses are not really an operator, but allow you to explicitly specifythe precedence of an operation. |
| Subscription |
| Attribute reference |
| Function call |
| |
xisNode xisnotNode | Type checking See alsois_instance_of()function. |
| Power Multiplies |
| Bitwise NOT |
+x -x | Identity / Negation |
x*y x/y x%y | Multiplication / Division / Remainder The Note: These operators have the same behavior as C++, which may beunexpected for users coming from Python, JavaScript, etc. See a detailednote after the table. |
x+y x-y | Addition (or Concatenation) / Subtraction |
x<<y x>>y | Bit shifting |
| Bitwise AND |
| Bitwise XOR |
| Bitwise OR |
x==y x!=y x<y x>y x<=y x>=y | Comparison See a detailed note after the table. |
xiny xnotiny | Inclusion checking
|
notx !x | Boolean NOT and itsunrecommended alias |
xandy x&&y | Boolean AND and itsunrecommended alias |
xory x||y | Boolean OR and itsunrecommended alias |
| Ternary if/else |
| |
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:
If both operands of the
/
operator areint, then integer division is performed instead of fractional. For example5/2==2
, not2.5
.If this is not desired, use at least onefloat literal (x/2.0
), cast (float(x)/y
), or multiply by1.0
(x*1.0/y
).The
%
operator is only available for ints, for floats use thefmod() function.For negative values, the
%
operator andfmod()
usetruncation instead of rounding towards negative infinity.This means that the remainder has a sign. If you need the remainder in a mathematical sense, use theposmod() andfposmod() functions instead.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 causea runtime error. If you're not sure about the types of the operands, you can safely use theis_same() function(but note that it is more strict about types and references). To compare floats, use theis_equal_approx()andis_zero_approx() functions instead.
Literals
Example(s) | Description |
| Null value |
| Boolean values |
| Base 10 integer |
| Base 16 (hexadecimal) integer |
| Base 2 (binary) integer |
| Floating-point number (real) |
| Regular strings |
| Triple-quoted regular strings |
| Raw strings |
| Triple-quoted raw strings |
| |
|
There are also two constructs that look like literals, but actually are not:
Example | Description |
| Shorthand for |
| Shorthand for |
Integers and floats can have their numbers separated with_
to make them more readable.The following ways to write numbers are all valid:
12_345_678# Equal to 12345678.3.141_592_7# Equal to 3.1415927.0x8080_0000_ffff# Equal to 0x80800000ffff.0b11_00_11_00# Equal to 0b11001100.
Regular string literals can contain the following escape sequences:
Escape sequence | Expands to |
| Newline (line feed) |
| Horizontal tab character |
| Carriage return |
| Alert (beep/bell) |
| Backspace |
| Formfeed page break |
| Vertical tab character |
| Double quote |
| Single quote |
| Backslash |
| UTF-16 Unicode codepoint |
| UTF-32 Unicode codepoint |
There are two ways to represent an escaped Unicode character above0xFFFF
:
as aUTF-16 surrogate pair
\uXXXX\uXXXX
.as a single UTF-32 codepoint
\UXXXXXX
.
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 totwo 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. A raw string literal doesn't process escape sequences,however it does recognize\\
and\"
(\'
) and replaces them with themselves.Thus, a string can have a quote that matches the opening one, but only if it's preceded by a backslash.
print("\tchar=\"\\t\"")# Prints ` char="\t"`.print(r"\tchar=\"\\t\"")# Prints `\tchar=\"\\t\"`.
Note
Some strings cannot be represented using raw string literals: you cannot have an odd numberof backslashes at the end of a string or have an unescaped opening quote inside the string.However, in practice this doesn't matter since you can use a different quote typeor use concatenation with a regular string literal.
GDScript also supportsformat strings.
Annotations
Annotations are special tokens in GDScript that act as modifiers to a script orits code and may affect how the script is treated by the Godot engine oreditor.
Every annotation starts with the@
character and is specified by a name. Adetailed description and example for each annotation can be found inside theGDScript class reference.
For instance, you can use it to export a value to the editor:
@export_range(1,100,1,"or_greater")varranged_var:int=50
For more information about exporting properties, read theGDScript exportsarticle.
Any constant expression compatible with the required argument type can be passed as an annotation argument value:
constMAX_SPEED=120.0@export_range(0.0,0.5*MAX_SPEED)varinitial_speed:float=0.25*MAX_SPEED
Annotations can be specified one per line or all in the same line. They affectthe next statement that isn't an annotation. Annotations can have arguments sentbetween parentheses and separated by commas.
Both of these are the same:
@annotation_a@annotation_bvarvariable@annotation_a@annotation_bvarvariable
@onready
annotation
When using nodes, it's common to desire to keep references to partsof the scene in a variable. As scenes are only warranted to beconfigured when entering the active scene tree, the sub-nodes can onlybe obtained when a call toNode._ready()
is made.
varmy_labelfunc_ready():my_label=get_node("MyLabel")
This can get a little cumbersome, especially when nodes and externalreferences pile up. For this, GDScript has the@onready
annotation, thatdefers initialization of a member variable until_ready()
is called. Itcan replace the above code with a single line:
@onreadyvarmy_label=get_node("MyLabel")
Warning
Applying@onready
and any@export
annotation to the same variabledoesn't work as you might expect. The@onready
annotation will causethe default value to be set after the@export
takes effect and willoverride it:
@exportvara="init_value_a"@onready@exportvarb="init_value_b"func_init():prints(a,b)# init_value_a <null>func_notification(what):ifwhat==NOTIFICATION_SCENE_INSTANTIATED:prints(a,b)# exported_value_a exported_value_bfunc_ready():prints(a,b)# exported_value_a init_value_b
Therefore, theONREADY_WITH_EXPORT
warning is generated, which is treatedas 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 isconsidered a comment.
# This is a comment.
Tip
In the Godot script editor, special keywords are highlighted within commentsto 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 themto be recognized:
# In the example below, "TODO" will appear in yellow by default.# The `:` symbol after the keyword is not required, but it's often used.# TODO: Add more items for the player to choose from.
The list of highlighted keywords and their colors can be changed in theTextEditor > Theme > Comment Markers section of the Editor Settings.
Use two hash symbols (##
) instead of one (#
) to add adocumentationcomment, which will appear in the script documentation and in the inspectordescription of an exported variable. Documentation comments must be placeddirectlyabove a documentable item (such as a member variable), or at the topof a file. Dedicated formatting options are also available. SeeGDScript documentation comments for details.
## This comment will appear in the script documentation.varvalue## This comment will appear in the inspector tooltip, and in the documentation.@exportvarexported_value
Code regions
Code regions are special types of comments that the script editor understands asfoldable regions. This means that after writing code region comments, you cancollapse and expand the region by clicking the arrow that appears at the left ofthe comment. This arrow appears within a purple square to be distinguishablefrom standard code folding.
The syntax is as follows:
# Important: There must be *no* space between the `#` and `region` or `endregion`.# Region without a description:#region...#endregion# Region with a description:#region Some description that is displayed even when collapsed...#endregion
Tip
To create a code region quickly, select several lines in the script editor,right-click the selection then chooseCreate Code Region. The regiondescription 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:
# This comment is outside the code region. It will be visible when collapsed.#region Terrain generation# This comment is inside the code region. It won't be visible when collapsed.funcgenerate_lakes():passfuncgenerate_hills():pass#endregion#region Terrain populationfuncplace_vegetation():passfuncplace_roads():pass#endregion
This can be useful to organize large chunks of code into easier to understandsections. However, remember that external editors generally don't support thisfeature, so make sure your code is easy to follow even when not relying onfolding code regions.
Note
Individual functions and indented sections (such asif
andfor
) canalways be collapsed in the script editor. This means you should avoidusing a code region to contain a single function or indented section, as itwon't bring much of a benefit. Code regions work best when they're used togroup 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 likeit's where the backslash is. Here is an example:
vara=1+ \2
A line can be continued multiple times like this:
vara=1+ \4+ \10+ \4
Built-in types
Built-in types are stack-allocated. They are passed as values. This means a copyis created on each assignment or when passing them as arguments to functions.The exceptions areObject
,Array
,Dictionary
, and packed arrays(such asPackedByteArray
), which are passed by reference so they are shared.All arrays,Dictionary
, and some objects (Node
,Resource
)have aduplicate()
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 notbe assigned any other value.
Only types that inherit from Object can have anull
value(Object is therefore called a "nullable" type).Variant types must have a valid value at all times,and therefore cannot have anull
value.
bool
Short for "boolean", it can only containtrue
orfalse
.
int
Short for "integer", it stores whole numbers (positive and negative).It is stored as a 64-bit value, equivalent toint64_t
in C++.
float
Stores real numbers, including decimals, using floating-point values.It is stored as a 64-bit value, equivalent todouble
in C++.Note: Currently, data structures such asVector2
,Vector3
, andPackedFloat32Array
store 32-bit single-precisionfloat
values.
String
A sequence of characters inUnicode format.
StringName
An immutable string that allows only one instance of each name. They are slower tocreate and may result in waiting for locks when multithreading. In exchange, they'revery 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 beeasily assigned to, and from, a String. They are useful to interact withthe tree to get a node, or affecting properties like withTweens.
Vector built-in types
Vector2
2D vector type containingx
andy
fields. Can also beaccessed as an array.
Vector2i
Same as a Vector2 but the components are integers. Useful for representingitems in a 2D grid.
Rect2
2D Rectangle type containing two vectors fields:position
andsize
.Also contains anend
field which isposition+size
.
Vector3
3D vector type containingx
,y
andz
fields. This can alsobe accessed as an array.
Vector3i
Same as Vector3 but the components are integers. Can be use for indexing itemsin a 3D grid.
Transform2D
3×2 matrix used for 2D transforms.
Plane
3D Plane type in normalized form that contains anormal
vector fieldand ad
scalar distance.
Quaternion
Quaternion is a datatype used for representing a 3D rotation. It'suseful for interpolating rotations.
AABB
Axis-aligned bounding box (or 3D box) contains 2 vectors fields:position
andsize
. Also contains anend
field which isposition+size
.
Basis
3x3 matrix used for 3D rotation and scale. It contains 3 vector fields(x
,y
andz
) and can also be accessed as an array of 3Dvectors.
Transform3D
3D Transform contains a Basis fieldbasis
and a Vector3 fieldorigin
.
Engine built-in types
Color
Color data type containsr
,g
,b
, anda
fields. It canalso be accessed ash
,s
, andv
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 index0
.Negative indices count from the end.
vararr=[]arr=[1,2,3]varb=arr[1]# This is 2.varc=arr[arr.size()-1]# This is 3.vard=arr[-1]# Same as the previous line, but shorter.arr[0]="Hi!"# Replacing value 1 with "Hi!".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 thatelement values match the specified type, so the array cannot contain invalid values.The GDScript static analyzer takes typed arrays into account, however array methods likefront()
andback()
still have theVariant
return type.
Typed arrays have the syntaxArray[Type]
, whereType
can be anyVariant
type,native or user class, or enum. Nested array types (likeArray[Array[int]]
) are not supported.
vara:Array[int]varb:Array[Node]varc:Array[MyClass]vard:Array[MyEnum]vare:Array[Variant]
Array
andArray[Variant]
are the same thing.
Note
Arrays are passed by reference, so the array element type is also an attribute of the in-memorystructure referenced by a variable in runtime. The static type of a variable restricts the structuresthat it can reference to. Therefore, youcannot assign an array with a different element type,even if the type is a subtype of the required type.
If you want toconvert a typed array, you can create a new array and use theArray.assign() method:
vara:Array[Node2D]=[Node2D.new()]# (OK) You can add the value to the array because `Node2D` extends `Node`.varb:Array[Node]=[a[0]]# (Error) You cannot assign an `Array[Node2D]` to an `Array[Node]` variable.b=a# (OK) But you can use the `assign()` method instead. Unlike the `=` operator,# the `assign()` method copies the contents of the array, not the reference.b.assign(a)
The only exception was made for theArray
(Array[Variant]
) type, for user convenienceand compatibility with old code. However, operations on untyped arrays are considered unsafe.
Packed arrays
PackedArrays are generally faster to iterate on and modify compared to a typedArray of the same type (e.g. PackedInt64Array versus Array[int]) and consumeless memory. In the worst case, they are expected to be as fast as an untypedArray. Conversely, non-Packed Arrays (typed or not) have extra conveniencemethods such asArray.map that PackedArrayslack. Consult theclass reference for detailson the methods available. Typed Arrays are generally faster to iterate on andmodify than untyped Arrays.
While all Arrays can cause memory fragmentation when they become large enough,if memory usage and performance (iteration and modification speed) is a concernand the type of data you're storing is compatible with one of thePacked
Array types, then using those may yield improvements. However, if you do nothave such concerns (e.g. the size of your array does not reach the tens ofthousands of elements) it is likely more helpful to use regular or typedArrays, as they provide convenience methods that can make your code easier towrite and maintain (and potentially faster if your data requires suchoperations a lot). If the data you will store is of a known type (includingyour own defined classes), prefer to use a typed Array as it may yield betterperformance in iteration and modification compared to an untyped Array.
PackedByteArray: An array of bytes (integers from 0 to 255).
PackedInt32Array: An array of 32-bit integers.
PackedInt64Array: An array of 64-bit integers.
PackedFloat32Array: An array of 32-bit floats.
PackedFloat64Array: An array of 64-bit floats.
PackedStringArray: An array of strings.
PackedVector2Array: An array ofVector2 values.
PackedVector3Array: An array ofVector3 values.
PackedVector4Array: An array ofVector4 values.
PackedColorArray: An array ofColor values.
Dictionary
Associative container which contains values referenced by unique keys.
vard={4:5,"A key":"A value",28:[1,2,3]}d["Hi!"]=0d={22:"value","some_key":2,"other_key":[2,3,4],"more_key":"Hello"}
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 GDScriptidentifier), and must be string literals.
vard={test22="value",some_key=2,other_key=[2,3,4],more_key="Hello"}
To add a key to an existing dictionary, access it like an existing key andassign to it:
vard={}# Create an empty Dictionary.d.waiting=14# Add String "waiting" as a key and assign the value 14 to it.d[4]="hello"# Add integer 4 as a key and assign the String "hello" as its value.d["Godot"]=3.01# Add String "Godot" as a key and assign the value 3.01 to it.vartest=4# Prints "hello" by indexing the dictionary with a dynamic key.# This is not the same as `d.test`. The bracket syntax equivalent to# `d.test` is `d["test"]`.print(d[test])
Note
The bracket syntax can be used to access properties of anyObject, not just Dictionaries. Keep in mind it will cause ascript error when attempting to index a non-existing property. To avoidthis, use theObject.get() andObject.set() methods instead.
Signal
A signal is a message that can be emitted by an object to those who want tolisten 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 asvalues (e.g. when connecting to signals).
Getting a method as a member returns a callable.varx=$Sprite2D.rotate
will set the value ofx
to a callable with$Sprite2D
as the object androtate
as the method.
You can call it using thecall
method:x.call(PI)
.
Variables
Variables can exist as class members or local to functions. They arecreated with thevar
keyword and may, optionally, be assigned avalue upon initialization.
vara# Data type is 'null' by default.varb=5varc=3.8vard=b+c# Variables are always initialized in direct order (see below).
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 assignan incompatible value will raise an error.
Types are specified in the variable declaration using a:
(colon) symbolafter the variable name, followed by the type.
varmy_vector2:Vector2varmy_node:Node=Sprite2D.new()
If the variable is initialized within the declaration, the type can be inferred, soit's possible to omit the type name:
varmy_vector2:=Vector2()# 'my_vector2' is of type 'Vector2'.varmy_node:=Sprite2D.new()# 'my_node' is of type 'Sprite2D'.
Type inference is only possible if the assigned value has a defined type, otherwiseit will raise an error.
Valid types are:
Built-in types (Array, Vector2, int, String, etc.).
Engine classes (Node, Resource, RefCounted, etc.).
Constant names if they contain a script resource (
MyScript
if you declaredconstMyScript=preload("res://my_script.gd")
).Other classes in the same script, respecting scope (
InnerClass.NestedClass
if you declaredclassNestedClass
inside theclassInnerClass
in the same scope).Script classes declared with the
class_name
keyword.Autoloads registered as singletons.
Note
WhileVariant
is a valid type specification, it's not an actual type. Itonly means there's no set type and is equivalent to not having a static typeat all. Therefore, inference is not allowed by default forVariant
,since it's likely a mistake.
You can turn off this check, or make it only a warning, by changing it inthe project settings. SeeGDScript warning system for details.
Initialization order
Member variables are initialized in the following order:
Depending on the variable's static type, the variable is either
null
(untyped variables and objects) or has a default value of the type(0
forint
,false
forbool
, etc.).The specified values are assigned in the order of the variables in the script,from top to bottom.
(Only for
Node
-derived classes) If the@onready
annotation is applied to a variable,its initialization is deferred to step 5.
If defined, the
_init()
method is called.When instantiating scenes and resources, the exported values are assigned.
(Only for
Node
-derived classes)@onready
variables are initialized.(Only for
Node
-derived classes) If defined, the_ready()
method is called.
Warning
You can specify a complex expression as a variable initializer, including function calls.Make sure the variables are initialized in the correct order, otherwise your valuesmay be overwritten. For example:
vara:int=proxy("a",1)varb:int=proxy("b",2)var_data:Dictionary={}funcproxy(key:String,value:int):_data[key]=valueprint(_data)returnvaluefunc_init()->void:print(_data)
Will print:
{"a":1}{"a":1,"b":2}{}
To fix this, move the_data
variable definition above thea
definitionor remove the empty dictionary assignment (={}
).
Static variables
A class member variable can be declared static:
staticvara
Static variables belong to the class, not instances. This means that static variablesshare 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 aPerson
class with a static variable namedmax_id
.We increment themax_id
in the_init()
function. This makes it easy to keep trackof the number ofPerson
instances in our game.
# person.gdclass_namePersonstaticvarmax_id=0varidvarnamefunc_init(p_name):max_id+=1id=max_idname=p_name
In this code, we create two instances of ourPerson
class and check that the classand every instance have the samemax_id
value, because the variable is static and accessible to every instance.
# test.gdextendsNodefunc_ready():varperson1=Person.new("John Doe")varperson2=Person.new("Jane Doe")print(person1.id)# 1print(person2.id)# 2print(Person.max_id)# 2print(person1.max_id)# 2print(person2.max_id)# 2
Static variables can have type hints, setters and getters:
staticvarbalance:int=0staticvardebt:int:get:return-balanceset(value):balance=-value
A base class static variable can also be accessed via a child class:
classA:staticvarx=1classBextendsA:passfunc_ready():prints(A.x,B.x)# 1 1A.x=2prints(A.x,B.x)# 2 2B.x=3prints(A.x,B.x)# 3 3
@static_unload
annotation
Since GDScript classes are resources, having static variables in a script prevents it from being unloadedeven if there are no more instances of that class and no other references left. This can be importantif 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_unloadannotation 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, beforeclass_name
andextends
:
@static_unloadclass_nameMyNodeextendsNode
See alsoStatic functions andStatic constructor.
Casting
Values assigned to typed variables must have a compatible type. If it's needed tocoerce a value to be of a certain type, in particular for object types, you canuse the casting operatoras
.
Casting between object types results in the same object if the value is of thesame type or a subtype of the cast type.
varmy_node2D:Node2Dmy_node2D=$Sprite2DasNode2D# Works since Sprite2D is a subtype of Node2D.
If the value is not a subtype, the casting operation will result in anull
value.
varmy_node2D:Node2Dmy_node2D=$ButtonasNode2D# Results in 'null' since a Button is not a subtype of Node2D.
For built-in types, they will be forcibly converted if possible, otherwise theengine will raise an error.
varmy_int:intmy_int="123"asint# The string can be converted to int.my_int=Vector2()asint# 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 withthe scene tree:
# Will infer the variable to be of type Sprite2D.varmy_sprite:=$CharacterasSprite2D# Will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()'.($AnimPlayerasAnimationPlayer).play("walk")
Constants
Constants are values you cannot change when the game is running.Their value must be known at compile-time. Using theconst
keyword allows you to give a constant value a name. Trying to assign avalue to a constant after it's declared will give you an error.
We recommend using constants whenever a value is not meant to change.
constA=5constB=Vector2(20,20)constC=10+20# Constant expression.constD=Vector2(20,30).x# Constant expression: 20.constE=[1,2,3,4][0]# Constant expression: 1.constF=sin(20)# 'sin()' can be used in constant expressions.constG=x+20# Invalid; this is not a constant expression!constH=A+20# Constant expression: 25 (`A` is a constant).
Although the type of constants is inferred from the assigned value, it's alsopossible to add explicit type specification:
constA:int=5constB: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 localmagic values.
Enums
Enums are basically a shorthand for constants, and are pretty useful if youwant to assign consecutive integers to some constant.
enum{TILE_BRICK,TILE_FLOOR,TILE_SPIKE,TILE_TELEPORT}# Is the same as:constTILE_BRICK=0constTILE_FLOOR=1constTILE_SPIKE=2constTILE_TELEPORT=3
If you pass a name to the enum, it will put all the keys inside a constantDictionary of that name. This means all constant methods ofa dictionary can also be used with a named enum.
Important
Keys in a named enum are not registeredas global constants. They should be accessed prefixedby the enum's name (Name.KEY
).
enumState{STATE_IDLE,STATE_JUMP=5,STATE_SHOOT}# Is the same as:constState={STATE_IDLE=0,STATE_JUMP=5,STATE_SHOOT=6}# Access values with State.STATE_IDLE, etc.func_ready():# Access values with Name.KEY, prints '5'print(State.STATE_JUMP)# Use dictionary methods:# prints '["STATE_IDLE", "STATE_JUMP", "STATE_SHOOT"]'print(State.keys())# prints '{ "STATE_IDLE": 0, "STATE_JUMP": 5, "STATE_SHOOT": 6 }'print(State)# prints '[0, 5, 6]'print(State.values())
If not assigning a value to a key of an enum it will be assigned the previous value plus one,or0
if it is the first entry in the enum. Multiple keys with the same value are allowed.
Functions
Functions always belong to aclass. The scope priority forvariable look-up is: local → class member → global. Theself
variable isalways available and is provided as an option for accessing class members(seeself), but is not always required (and shouldnot be sent as thefunction's first argument, unlike Python).
funcmy_function(a,b):print(a)print(b)returna+b# Return is optional; without it 'null' is returned.
A function canreturn
at any point. The default return value isnull
.
If a function contains only one line of code, it can be written on one line:
funcsquare(a):returna*afunchello_world():print("Hello World")funcempty_function():pass
Functions can also have type specification for the arguments and for the returnvalue. Types for arguments can be added in a similar way to variables:
funcmy_function(a:int,b:String):pass
If a function argument has a default value, it's possible to infer the type:
funcmy_function(int_arg:=42,String_arg:="string"):pass
The return type of the function can be specified after the arguments list usingthe arrow token (->
):
funcmy_int_function()->int:return0
Functions that have a return typemust return a proper value. Setting thetype asvoid
means the function doesn't return anything. Void functions canreturn early with thereturn
keyword, but they can't return any value.
funcvoid_function()->void:return# Can't return a value.
Note
Non-void functions mustalways return a value, so if your code hasbranching statements (such as anif
/else
construct), all thepossible paths must have a return. E.g., if you have areturn
inside anif
block but not after it, the editor will raise anerror because if the block is not executed, the function won't have avalid value to return.
Referencing functions
Functions are first-class values in terms of theCallable object.Referencing a function by name without calling it will automatically generate the propercallable. This can be used to pass functions as arguments.
funcmap(arr:Array,function:Callable)->Array:varresult=[]foriteminarr:result.push_back(function.call(item))returnresultfuncadd1(value:int)->int:returnvalue+1;func_ready()->void:varmy_array=[1,2,3]varplus_one=map(my_array,add1)print(plus_one)# Prints `[2, 3, 4]`.
Note
Callablesmust be called with thecall() method.You cannot use the()
operator directly. This behavior is implemented to avoidperformance issues on direct function calls.
Lambda functions
Lambda functions allow you to declare functions that do not belong to a class. Instead, aCallable object is created and assigned to a variable directly.This can be useful to create callables to pass around without polluting the class scope.
varlambda=func(x):print(x)
To call the created lambda you can use thecall() method:
lambda.call(42)# Prints `42`.
Lambda functions can be named for debugging purposes (the name is displayed in the Debugger):
varlambda=funcmy_lambda(x):print(x)
You can specify type hints for lambda functions in the same way as for regular ones:
varlambda:=func(x:int)->void:print(x)
Note that if you want to return a value from a lambda function, an explicitreturn
is required (you can't omitreturn
):
varlambda=func(x):returnx**2print(lambda.call(2))# Prints `4`.
Lambda functions capture the local environment:
varx=42varlambda=func():print(x)# Prints `42`.lambda.call()
Warning
Local variables are captured by value once, when the lambda is created.So they won't be updated in the lambda if reassigned in the outer function:
varx=42varlambda=func():print(x)lambda.call()# Prints `42`.x="Hello"lambda.call()# Prints `42`.
Also, a lambda cannot reassign an outer local variable. After exiting the lambda,the variable will be unchanged, because the lambda capture implicitly shadows it:
varx=42varlambda=func():print(x)# Prints `42`.x="Hello"# Produces the `CONFUSABLE_CAPTURE_REASSIGNMENT` warning.print(x)# Prints `Hello`.lambda.call()print(x)# Prints `42`.
However, if you use pass-by-reference data types (arrays, dictionaries, and objects),then the content changes are shared until you reassign the variable:
vara=[]varlambda=func():a.append(1)print(a)# Prints `[1]`.a=[2]# Produces the `CONFUSABLE_CAPTURE_REASSIGNMENT` warning.print(a)# Prints `[2]`.lambda.call()print(a)# Prints `[1]`.
Static functions
A function can be declared static. When a function is static, it has no access to the instance member variables orself
.A static function has access to static variables. Also static functions are useful to make libraries of helper functions:
staticfuncsum2(a,b):returna+b
Lambda functions cannot be declared static.
See alsoStatic variables andStatic constructor.
Statements and control flow
Statements are standard and can be assignments, function calls, controlflow structures, etc (see below).;
as a statement separator isentirely optional.
Expressions
Expressions are sequences of operators and their operands in orderly fashion. An expression by itself can be astatement 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 anotherexpression. An assignment is not an expression and thus does not return any value.
Here are some examples of expressions:
2+2# Binary operation.-5# Unary operation."okay"ifx>4else"not okay"# Ternary operation.x# Identifier representing variable or constant.x.a# Attribute access.x[4]# Subscript access.x>2orx<5# Comparisons and logic operators.x==y+2# Equality test.do_something()# Function call.[1,2,3]# Array definition.{A=1,B=2}# Dictionary definition.preload("res://icon.png")# Preload builtin function.self# Reference to current instance.
Identifiers, attributes, and subscripts are valid assignment targets. Other expressions cannot be on the left side ofan assignment.
self
self
can be used to refer to the current instance and is often equivalent todirectly referring to symbols available in the current script. However,self
also allows you to access properties, methods, and other names that are defineddynamically (i.e. are expected to exist in subtypes of the current class, or areprovided using_set() and/or_get()).
extendsNodefunc_ready():# Compile time error, as `my_var` is not defined in the current class or its ancestors.print(my_var)# Checked at runtime, thus may work for dynamic properties or descendant classes.print(self.my_var)# Compile time error, as `my_func()` is not defined in the current class or its ancestors.my_func()# Checked at runtime, thus may work for descendant classes.self.my_func()
Warning
Beware that accessing members of child classes in the base class is oftenconsidered a bad practice, because this blurs the area of responsibility ofany given piece of code, making the overall relationship between parts ofyour game harder to reason about. Besides that, one can simply forget thatthe parent class had some expectations about it's descendants.
if/else/elif
Simple conditions are created by using theif
/else
/elif
syntax.Parenthesis around conditions are allowed, but not required. Given thenature of the tab-based indentation,elif
can be used instead ofelse
/if
to maintain a level of indentation.
if(expression):statement(s)elif(expression):statement(s)else:statement(s)
Short statements can be written on the same line as the condition:
if1+1==2:return2+2else:varx=3+3returnx
Sometimes, you might want to assign a different initial value based on aboolean expression. In this case, ternary-if expressions come in handy:
varx=(value)if(expression)else(value)y+=3ify<10else-1
Ternary-if expressions can be nested to handle more than 2 cases. When nestingternary-if expressions, it is recommended to wrap the complete expression overmultiple lines to preserve readability:
varcount=0varfruit=("apple"ifcount==2else"pear"ifcount==1else"banana"ifcount==0else"orange")print(fruit)# banana# Alternative syntax with backslashes instead of parentheses (for multi-line expressions).# Less lines required, but harder to refactor.varfruit_alt= \"apple"ifcount==2 \else"pear"ifcount==1 \else"banana"ifcount==0 \else"orange"print(fruit_alt)# banana
You may also wish to check if a value is contained within something. You canuse anif
statement combined with thein
operator to accomplish this:
# Check if a letter is in a string.vartext="abc"if'b'intext:print("The string contains b")# Check if a variable is contained within a node.if"varName"inget_parent():print("varName is defined in parent!")
while
Simple loops are created by usingwhile
syntax. Loops can be brokenusingbreak
or continued usingcontinue
(which skips to the nextiteration of the loop without executing any further code in the current iteration):
while(expression):statement(s)
for
To iterate through a range, such as an array or table, afor loop isused. When iterating over an array, the current array element is stored inthe loop variable. When iterating over a dictionary, thekey is storedin the loop variable.
forxin[5,7,11]:statement# Loop iterates 3 times with 'x' as 5, then 7 and finally 11.varnames=["John","Marta","Samantha","Jimmy"]forname:Stringinnames:# Typed loop variable.print(name)# Prints name's content.vardict={"a":0,"b":1,"c":2}foriindict:print(dict[i])# Prints 0, then 1, then 2.foriinrange(3):statement# Similar to [0, 1, 2] but does not allocate an array.foriinrange(1,3):statement# Similar to [1, 2] but does not allocate an array.foriinrange(2,8,2):statement# Similar to [2, 4, 6] but does not allocate an array.foriinrange(8,2,-2):statement# Similar to [8, 6, 4] but does not allocate an array.forcin"Hello":print(c)# Iterate through all characters in a String, print every letter on new line.foriin3:statement# Similar to range(3).foriin2.2:statement# Similar to range(ceil(2.2)).
If you want to assign values on an array as it is being iterated through, itis best to useforiinarray.size()
.
foriinarray.size():array[i]="Hello World"
The loop variable is local to the for-loop and assigning to it will not changethe value on the array. Objects passed by reference (such as nodes) can stillbe manipulated by calling methods on the loop variable.
forstringinstring_array:string="Hello World"# This has no effectfornodeinnode_array:node.add_to_group("Cool_Group")# This has an effect
match
Amatch
statement is used to branch execution of a program.It's the equivalent of theswitch
statement found in many other languages, but offers some additional features.
Warning
match
is more type strict than the==
operator. For example1
willnot match1.0
. The only exception isString
vsStringName
matching:for example, the String"hello"
is considered equal to the StringName&"hello"
.
Basic syntax
match<testvalue>:<pattern(s)>:<block><pattern(s)>when<patternguard>:<block><...>
Crash-course for people who are familiar with switch statements
Replace
switch
withmatch
.Remove
case
.Remove any
break
s.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 thematch
statement.
Note
The specialcontinue
behavior inmatch
supported in 3.x was removed in Godot 4.0.
The following pattern types are available:
- Literal pattern
Matches aliteral:
matchx:1:print("We are number one!")2:print("Two are better than one!")"test":print("Oh snap! It's a string!")
- Expression pattern
Matches a constant expression, an identifier, or an attribute access (
A.B
):matchtypeof(x):TYPE_FLOAT:print("float")TYPE_STRING:print("text")TYPE_ARRAY: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 aswitch
statement in other languages:matchx:1:print("It's one!")2:print("It's one times two!")_: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:
matchx:1:print("It's one!")2:print("It's one times two!")varnew_var: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.
matchx:[]:print("Empty array")[1,3,"test",null]:print("Very specific array")[varstart,_,"test"]:print("First element is ",start,", and the last is\"test\"")[42,..]: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
:
.matchx:{}:print("Empty dict"){"name":"Dennis"}:print("The name is Dennis"){"name":"Dennis","age":varage}:print("Dennis is ",age," years old."){"name","age"}:print("Has a name and an age, but it's not Dennis :("){"key":"godotisawesome",..}: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.
matchx:1,2,3:print("It's 1 - 3")"Sword","Splash potion","Fist":print("Yep, you've taken damage")
Pattern guards
Apattern guard is an optional condition that follows the pattern listand allows you to make additional checks before choosing amatch
branch.Unlike a pattern, a pattern guard can be an arbitrary expression.
Only one branch can be executed permatch
. 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 pattern guard after the list of patterns with thewhen
keyword:
matchpoint:[0,0]:print("Origin")[_,0]:print("Point on X-axis")[0,_]:print("Point on Y-axis")[varx,vary]wheny==x:print("Point on line y = x")[varx,vary]wheny==-x:print("Point on line y = -x")[varx,vary]:print("Point (%s,%s)"%[x,y])
If there is no matching pattern for the current branch, the pattern guardisnot evaluated and the patterns of the next branch are checked.
If a matching pattern is found, the pattern guard 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 onlyreference them using the file's path, using either a relative or an absolutepath. For example, if you name a script filecharacter.gd
:
# Inherit from 'character.gd'.extends"res://path/to/character.gd"# Load character.gd and create a new node instance from it.varCharacter=load("res://path/to/character.gd")varcharacter_node=Character.new()
Registering named classes
You can give your class a name to register it as a new type in Godot'seditor. For that, you use theclass_name
keyword. You can optionally usethe@icon
annotation with a path to an image, to use it as an icon. Yourclass will then appear with its new icon in the editor:
# item.gd@icon("res://interface/icons/item.png")class_nameItemextendsNode

Tip
SVG images that are used as custom node icons should have theEditor > Scale With Editor Scale andEditor > Convert Icons With Editor Themeimport options enabled. This allowsicons to follow the editor's scale and theming settings if the icons are designed withthe same color palette as Godot's own icons.
Here's a class file example:
# Saved as a file named 'character.gd'.class_nameCharactervarhealth=5funcprint_health():print(health)funcprint_this_script_three_times():print(get_script())print(ResourceLoader.load("res://character.gd"))print(Character)
If you want to useextends
too, you can keep both on the same line:
class_nameMyNodeextendsNode
Named classes are globally registered, which means they become available to usein other scripts without the need toload
orpreload
them:
varplayerfunc_ready():player=Character.new()
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.
Warning
The Godot editor will hide these custom classes with names that begin with the prefix"Editor" in the 'Create New Node' or 'Create New Scene' dialog windows. The classesare available for instantiation at runtime via their class names, but areautomatically hidden by the editor windows along with the built-in editor nodes usedby the Godot editor.
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 theextends
keyword:
# Inherit/extend a globally available class.extendsSomeClass# Inherit/extend a named class file.extends"somefile.gd"# Inherit/extend an inner class in another file.extends"somefile.gd".SomeInnerClass
Note
If inheritance is not explicitly defined, the class will default to inheritingRefCounted.
To check if a given instance inherits from a given class,theis
keyword can be used:
# Cache the enemy class.constEnemy=preload("enemy.gd")# [...]# Use 'is' to check inheritance.ifentityisEnemy:entity.apply_damage()
To call a function in asuper class (i.e. oneextend
-ed in your currentclass), use thesuper
keyword:
super(args)
This is especially useful because functions in extending classes replacefunctions with the same name in their super classes. If you still want tocall them, you can usesuper
:
funcsome_func(x):super(x)# Calls the same function on the super class.
If you need to call a different function from the super class, you can specifythe function name with the attribute operator:
funcoverriding():return0# This overrides the method in the base class.funcdont_override():returnsuper.overriding()# This calls the method as defined in the base class.
Warning
One of the common misconceptions is trying to overridenon-virtual engine methodssuch asget_class()
,queue_free()
, etc. This is not supported for technical reasons.
In Godot 3, you canshadow engine methods in GDScript, and it will work if you call this method in GDScript.However, the engine willnot 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 theNATIVE_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 thevirtual
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 youwant to call the base class constructor, you can also use thesuper
syntax.Note that every class has an implicit constructor that is always called(defining the default values of class variables).super
is used to call theexplicit constructor:
func_init(arg):super("some_default",arg)# Call the custom base constructor.
This is better explained through examples. Consider this scenario:
# state.gd (inherited class).varentity=nullvarmessage=nullfunc_init(e=null):entity=efuncenter(m):message=m# idle.gd (inheriting class).extends"state.gd"func_init(e=null,m=null):super(e)# Do something with 'e'.message=m
There are a few things to keep in mind here:
If the inherited class (
state.gd
) defines a_init
constructor that takesarguments (e
in this case), then the inheriting class (idle.gd
)mustdefine_init
as well and pass appropriate parameters to_init
fromstate.gd
.idle.gd
can have a different number of arguments than the base classstate.gd
.In the example above,
e
passed to thestate.gd
constructor is the samee
passedin toidle.gd
.If
idle.gd
's_init
constructor takes 0 arguments, it still needs to pass some valueto thestate.gd
base class, even if it does nothing. This brings us to the fact that youcan pass expressions to the base constructor as well, not just variables, e.g.:# idle.gdfunc_init():super(5)
Static constructor
A static constructor is a static function_static_init
that is called automaticallywhen the class is loaded, after the static variables have been initialized:
staticvarmy_static_var=1staticfunc_static_init():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 theclass
keyword. They are instanced using theClassName.new()
function.
# Inside a class file.# An inner class in this class file.classSomeInnerClass:vara=5funcprint_value_of_a():print(a)# This is the constructor of the class file's main class.func_init():varc=SomeInnerClass.new()c.print_value_of_a()
Classes as resources
Classes stored as files are treated asGDScripts. Theymust be loaded from disk to access them in other classes. This is done usingeither theload
orpreload
functions (see below). Instancing of a loadedclass resource is done by calling thenew
function on the class object:
# Load the class resource when calling load().varMyClass=load("myclass.gd")# Preload the class only once at compile time.constMyClass=preload("myclass.gd")func_init():vara=MyClass.new()a.some_function()
Exports
Note
Documentation about exports has been moved toGDScript exported properties.
Properties (setters and getters)
Sometimes, you want a class' member variable to do more than just hold data and actually performsome validation or computation whenever its value changes. It may also be desired toencapsulate its access in some way.
For this, GDScript provides a special syntax to define properties using theset
andget
keywords after a variable declaration. Then you can define a code block that will be executedwhen the variable is accessed or assigned.
Example:
varmilliseconds:int=0varseconds:int:get:returnmilliseconds/1000set(value):milliseconds=value*1000
Note
Unlikesetget
in previous Godot versions,set
andget
methods arealways called (except as noted below),even when accessed inside the same class (with or without prefixing withself.
). This makes the behaviorconsistent. If you need direct access to the value, use another variable for direct access and make the propertycode 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 declarationor you need to reuse the code across multiple properties (but you can't distinguish which property the setter/getter is being called for):
varmy_prop:get=get_my_prop,set=set_my_prop
This can also be done in the same line:
varmy_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 forinline 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:
signalchanged(new_value)varwarns_when_changed="some value":get:returnwarns_when_changedset(value):changed.emit(value)warns_when_changed=value
This also applies to the alternative syntax:
varmy_prop:set=set_my_propfuncset_my_prop(value):my_prop=value# No infinite recursion.
Warning
The exception doesnot propagate to other functions called in the setter/getter.For example, the following codewill cause an infinite recursion:
varmy_prop:set(value):set_my_prop(value)funcset_my_prop(value):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 exportedproperties can be changed. In some cases, it is desired that they do runinside the editor (as long as they don't execute game code or manuallyavoid doing so). For this, the@tool
annotation exists and must beplaced at the top of the file:
@toolextendsButtonfunc_ready():print("Hello")
SeeRunning code in the editor for more information.
Warning
Be cautious when freeing nodes withqueue_free()
orfree()
in a tool script (especially the script's owner itself). As toolscripts run their code in the editor, misusing them may lead tocrashing the editor.
Memory management
Godot implements reference counting to free certain instances that are no longerused, instead of a garbage collector, or requiring purely manual management.Any instance of theRefCounted class (or any class that inheritsit, such asResource) will be freed automatically when no longerin use. For an instance of any class that is not aRefCounted(such asNode or the baseObject type), it willremain in memory until it is deleted withfree()
(orqueue_free()
for Nodes).
Note
If aNode is deleted viafree()
orqueue_free()
,all of its children will also recursively be deleted.
To avoid reference cycles that can't be freed, aWeakReffunction is provided for creating weak references, which allow accessto the object without preventing aRefCounted from freeing.Here is an example:
extendsNodevarmy_file_reffunc_ready():varf=FileAccess.open("user://example_file.json",FileAccess.READ)my_file_ref=weakref(f)# the FileAccess class inherits RefCounted, so it will be freed when not in use# the WeakRef will not prevent f from being freed when other_node is finishedother_node.use_file(f)func_this_is_called_later():varmy_file=my_file_ref.get_ref()ifmy_file:my_file.close()
Alternatively, when not using references, theis_instance_valid(instance)
can be used to check if an object has beenfreed.
Signals
Signals are a tool to emit messages from an object that other objects can reactto. To create custom signals for a class, use thesignal
keyword.
extendsNode# A signal named health_depleted.signalhealth_depleted
Note
Signals are aCallbackmechanism. They also fill the role of Observers, a common programmingpattern. For more information, read theObserver tutorial in theGame Programming Patterns ebook.
You can connect these signals to methods the same way you connect built-insignals of nodes likeButton orRigidBody3D.
In the example below, we connect thehealth_depleted
signal from aCharacter
node to aGame
node. When theCharacter
node emits thesignal, the game node's_on_character_health_depleted
is called:
# game.gdfunc_ready():varcharacter_node=get_node('Character')character_node.health_depleted.connect(_on_character_health_depleted)func_on_character_health_depleted():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 screento react to health changes with an animation, but we want to keep the userinterface separate from the player in our scene tree.
In ourcharacter.gd
script, we define ahealth_changed
signal and emitit withSignal.emit(), and fromaGame
node higher up our scene tree, we connect it to theLifebar
usingtheSignal.connect() method:
# character.gd...signalhealth_changedfunctake_damage(amount):varold_health=healthhealth-=amount# We emit the health_changed signal every time the# character takes damage.health_changed.emit(old_health,health)...
# lifebar.gd# Here, we define a function to use as a callback when the# character's health_changed signal is emitted....func_on_Character_health_changed(old_value,new_value):ifold_value>new_value:progress_bar.modulate=Color.REDelse:progress_bar.modulate=Color.GREEN# Imagine that `animate` is a user-defined function that animates the# bar filling up or emptying itself.progress_bar.animate(old_value,new_value)...
In theGame
node, we get both theCharacter
andLifebar
nodes, thenconnect the character, that emits the signal, to the receiver, theLifebar
node in this case.
# game.gdfunc_ready():varcharacter_node=get_node('Character')varlifebar_node=get_node('UserInterface/Lifebar')character_node.health_changed.connect(lifebar_node._on_Character_health_changed)
This allows theLifebar
to react to health changes without coupling it totheCharacter
node.
You can write optional argument names in parentheses after the signal'sdefinition:
# Defining a signal that forwards two arguments.signalhealth_changed(old_value,new_value)
These arguments show up in the editor's node dock, and Godot can use them togenerate callback functions for you. However, you can still emit any number ofarguments when you emit signals; it's up to you to emit the correct values.

You can also create copies of GDScript Callable objects which accept additionalarguments usingCallable.bind(). Thisallows you to add extra information to the connection if the emitted signalitself doesn't give you access to all the data that you need.
When the signal is emitted, the callback method receives the bound values, inaddition to those provided by the signal.
Building on the example above, let's say we want to display a log of the damagetaken by each character on the screen, likePlayer1took22damage.
. Thehealth_changed
signal doesn't give us the name of the character that tookdamage. So when we connect the signal to the in-game console, we can add thecharacter's name using the bind method:
# game.gdfunc_ready():varcharacter_node=get_node('Character')varbattle_log_node=get_node('UserInterface/BattleLog')character_node.health_changed.connect(battle_log_node._on_Character_health_changed.bind(character_node.name))
OurBattleLog
node receives each bound element as an extra argument:
# battle_log.gdfunc_on_Character_health_changed(old_value,new_value,character_name):ifnotnew_value<=old_value:returnvardamage=old_value-new_valuelabel.text+=character_name+" took "+str(damage)+" damage."
Awaiting signals or coroutines
Theawait
keyword can be used to createcoroutineswhich wait until a signal is emitted before continuing execution. Using theawait
keyword with a signal or acall to a function that is also a coroutine will immediately return the control to the caller. When the signal isemitted (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:
funcwait_confirmation():print("Prompting user")await$Button.button_up# Waits for the button_up signal from Button node.print("User confirmed")returntrue
In this case, thewait_confirmation
becomes a coroutine, which means that the caller also needs to await it:
funcrequest_confirmation():print("Will ask the user")varconfirmed=awaitwait_confirmation()ifconfirmed:print("User confirmed")else:print("User cancelled")
Note that requesting a coroutine's return value withoutawait
will trigger an error:
funcwrong():varconfirmed=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'tmake the current function a coroutine:
funcokay():wait_confirmation()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 thefunction won't give the control back to the caller:
funcno_wait():varx=awaitget_five()print("This doesn't make this function a coroutine.")funcget_five():return5
This also means that returning a signal from a function that isn't a coroutine will make the caller await that signal:
funcget_signal():return$Button.button_upfuncwait_button():awaitget_signal()print("Button was pressed")
Note
Unlikeyield
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 anint
while it actually returns a function state objectduring runtime.
Assert keyword
Theassert
keyword can be used to check conditions in debug builds. Theseassertions are ignored in non-debug builds. This means that the expressionpassed as argument won't be evaluated in a project exported in release mode.Due to this, assertions mustnot contain expressions that haveside effects. Otherwise, the behavior of the script would varydepending on whether the project is run in a debug build.
# Check that 'i' is 0. If 'i' is not 0, an assertion error will occur.assert(i==0)
When running a project from the editor, the project will be paused if anassertion error occurs.
You can optionally pass a custom error message to be shown if the assertionfails:
assert(enemy_power<256,"Enemy is too powerful!")