GDScript basics¶
Introduction¶
GDScript is a high-level, dynamically typed programming language used tocreate content. It uses a syntax similar toPython(blocks are indent-based and many keywords are similar). Its goal isto be optimized for and tightly integrated with Godot Engine, allowing greatflexibility for content creation and integration.
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 a simple example of how GDScript looks.
# A file is a class!# InheritanceextendsBaseClass# (optional) class definition with a custom iconclass_nameMyClass,"res://path/to/optional/icon.svg"# Member variablesvara=5vars="Hello"vararr=[1,2,3]vardict={"key":"value",2:3}vartyped_var:intvarinferred_type:="String"# ConstantsconstANSWER=42constTHE_NAME="Charly"# Enumsenum{UNIT_NEUTRAL,UNIT_ENEMY,UNIT_ALLY}enumNamed{THING_1,THING_2,ANOTHER_THING=-1}# Built-in vector typesvarv2=Vector2(1,2)varv3=Vector3(1,2,3)# Functionfuncsome_function(param1,param2):varlocal_var=5ifparam1<local_var:print(param1)elifparam2>5:print(param2)else:print("Fail!")foriinrange(20):print(i)whileparam2!=0:param2-=1varlocal_var2=param1+3returnlocal_var2# Functions override functions with the same name on the base/parent class.# If you still want to call them, use '.' (like 'super' in other languages).funcsomething(p1,p2):.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.
Language¶
In the following, an overview is given to GDScript. Details, such as whichmethods are available to arrays or other objects, should be looked up inthe linked class descriptions.
Identifiers¶
Any string that restricts itself to alphabetic characters (a toz andA toZ), digits (0 to9) and_ qualifiesas an identifier. Additionally, identifiers must not begin with a digit.Identifiers are case-sensitive (foo is different fromFOO).
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. |
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. |
class_name | Defines a class name and optional icon for your script. |
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. |
as | Cast the value to a given type if possible. |
self | Refers to current class instance. |
tool | Executes the script in the editor. |
signal | Defines a signal. |
func | Defines a function. |
static | Defines a static function. Static member variables are not allowed. |
const | Defines a constant. |
enum | Defines an enum. |
var | Defines a variable. |
onready | Initializes a variable once the Node the script is attached to and its children are part of the scene tree. |
export | Saves a variable along with the resource it's attached to and makes it visible and modifiable in the editor. |
setget | Defines setter and getter functions for a variable. |
breakpoint | Editor helper for debugger breakpoints. |
preload | Preloads a class or variable. SeeClasses as resources. |
yield | Coroutine support. SeeCoroutines with yield. |
assert | Asserts a condition, logs error on failure. Ignored in non-debug builds. SeeAssert keyword. |
remote | Networking RPC annotation. Seehigh-level multiplayer docs. |
master | Networking RPC annotation. Seehigh-level multiplayer docs. |
puppet | Networking RPC annotation. Seehigh-level multiplayer docs. |
remotesync | Networking RPC annotation. Seehigh-level multiplayer docs. |
mastersync | Networking RPC annotation. Seehigh-level multiplayer docs. |
puppetsync | Networking RPC annotation. Seehigh-level multiplayer docs. |
PI | PI constant. |
TAU | TAU constant. |
INF | Infinity constant. Used for comparisons. |
NAN | NAN (not a number) constant. Used for comparisons. |
Operators¶
The following is the list of supported operators and their precedence.
Operator | Description |
| Subscription (highest priority) |
| Attribute reference |
| Function call |
| Instance type checker |
| Bitwise NOT |
| Negative / Unary negation |
| Multiplication / Division / Remainder These operators have the same behavioras C++. Integer division is truncatedrather than returning a fractionalnumber, and the % operator is onlyavailable for ints ("fmod" for floats),and is additionally used for FormatStrings |
| Addition / Concatenation of arrays |
| Subtraction |
| Bit shifting |
| Bitwise AND |
| Bitwise XOR |
| Bitwise OR |
| Comparisons |
| Content test |
| Boolean NOT |
| Boolean AND |
| Boolean OR |
| Ternary if/else |
| Type casting |
| Assignment (lowest priority) |
Literals¶
Literal | Type |
| Base 10 integer |
| Base 16 (hexadecimal) integer |
| Base 2 (binary) integer |
| Floating-point number (real) |
| Strings |
| Multiline string |
| NodePath or StringName |
| 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.
Comments¶
Anything from a# to the end of the line is ignored and isconsidered a comment.
# This is a comment.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 only exceptions areArrays andDictionaries, which are passed byreference so they are shared. (Pooled arrays such asPoolByteArray are stillpassed as values.)
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.
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 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, andPoolRealArray store 32-bit single-precision "float" values.
String¶
A sequence of characters inUnicode format.Strings 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 |
| Unicode codepoint |
GDScript also supportsGDScript format strings.
Vector built-in types¶
Vector2¶
2D vector type containingx andy fields. Can also beaccessed as an array.
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.
Transform2D¶
3×2 matrix used for 2D transforms.
Plane¶
3D Plane type in normalized form that contains anormal vector fieldand ad scalar distance.
Quat¶
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:positionandsize. 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.
Transform¶
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.
NodePath¶
Compiled path to a node used mainly in the scene system. It can beeasily assigned to, and from, a String.
RID¶
Resource ID (RID). Servers use generic RIDs to reference opaque data.
Object¶
Base class for anything that is not a built-in type.
Container built-in types¶
Array¶
Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).The array can resize dynamically. Arrays are indexed starting from 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].
GDScript arrays are allocated linearly in memory for speed.Large arrays (more than tens of thousands of elements) may however causememory fragmentation. If this is a concern, special types ofarrays are available. These only accept a single data type. They avoid memoryfragmentation and use less memory, but are atomic and tend to run slower than genericarrays. They are therefore only recommended to use for large data sets:
PoolByteArray: An array of bytes (integers from 0 to 255).
PoolIntArray: An array of integers.
PoolRealArray: An array of floats.
PoolStringArray: An array of strings.
PoolVector2Array: An array ofVector2 objects.
PoolVector3Array: An array ofVector3 objects.
PoolColorArray: An array ofColor objects.
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).
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.
Data¶
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 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 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=Sprite.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:=Sprite.new()# 'my_node' is of type 'Sprite'.
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, Reference, etc.).
Constant names if they contain a script resource (
MyScriptif you declaredconstMyScript=preload("res://my_script.gd")).Other classes in the same script, respecting scope (
InnerClass.NestedClassif you declaredclassNestedClassinside theclassInnerClassin the same scope).Script classes declared with the
class_namekeyword.
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=$SpriteasNode2D# Works since Sprite 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 Sprite.varmy_sprite:=$CharacterasSprite# 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.
Note
Since arrays and dictionaries are passed by reference, constants are "flat".This means that if you declare a constant array or dictionary, it can stillbe modified afterwards. They can't be reassigned with another value though.
Enums¶
Enums are basically a shorthand for constants, and are pretty useful if youwant to assign consecutive integers to some constant.
If you pass a name to the enum, it will put all the keys inside a constantdictionary of that name.
Important
In Godot 3.1 and later, keys in a named enum are not registeredas global constants. They should be accessed prefixed by theenum's name (Name.KEY); see an example below.
enum{TILE_BRICK,TILE_FLOOR,TILE_SPIKE,TILE_TELEPORT}# Is the same as:constTILE_BRICK=0constTILE_FLOOR=1constTILE_SPIKE=2constTILE_TELEPORT=3enumState{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.
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, butis not always required (and shouldnot be sent as the function's firstargument, 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.
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 areturninside 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¶
Contrary to Python, functions arenot first-class objects in GDScript. Thismeans they cannot be stored in variables, passed as an argument to anotherfunction or be returned from other functions. This is for performance reasons.
To reference a function by name at run-time, (e.g. to store it in a variable, orpass it to another function as an argument) one must use thecall orfuncref helpers:
# Call a function by name in one step.my_node.call("my_function",args)# Store a function reference.varmy_func=funcref(my_node,"my_function")# Call stored function reference.my_func.call_func(args)
Static functions¶
A function can be declared static. When a function is static, it has noaccess to the instance member variables orself. This is mainlyuseful to make libraries of helper functions:
staticfuncsum2(a,b):returna+b
Statements and control flow¶
Statements are standard and can be assignments, function calls, controlflow structures, etc (see below).; as a statement separator isentirely optional.
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
while¶
Simple loops are created by usingwhile syntax. Loops can be brokenusingbreak or continued usingcontinue:
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.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.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))
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.
Basic syntax:
match[expression]:[pattern](s):[block][pattern](s):[block][pattern](s):[block]
Crash-course for people who are familiar with switch statements:
Replace
switchwithmatch.Remove
case.Remove any
breaks. If you don't want tobreakby default, you can usecontinuefor a fallthrough.Change
defaultto 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.You can usecontinue to stop execution in the current block and check for an additional match in the patterns below it.
There are 6 pattern types:
- Constant pattern
Constant primitives, like numbers and strings:
matchx:1:print("We are number one!")2:print("Two are better than one!")"test":print("Oh snap! It's a string!")
- Variable pattern
Matches the contents of a variable/enum:
matchtypeof(x):TYPE_REAL: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
defaultin aswitchstatement 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")
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 adda comma followed by a path to an image, to use it as an icon. Yourclass will then appear with its new icon in the editor:
# Item.gdextendsNodeclass_nameItem,"res://interface/icons/item.png"

Warning
If the script is located in theres://addons/ directory,class_namewill only cause the node to show up in theCreate New Node dialog ifthe script is part of anenabled editor plugin. SeeMaking pluginsfor more information.
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)
Note
Godot's class syntax is compact: it can only contain member variables orfunctions. You can use static functions, but not static member variables. In thesame way, the engine initializes variables every time you create an instance,and this includes arrays and dictionaries. This is in the spirit of threadsafety, since scripts can be initialized in separate threads without the userknowing.
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
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 aparent class (i.e. oneextend-ed in your currentclass), prepend. to the function name:
.base_func(args)
This is especially useful because functions in extending classes replacefunctions with the same name in their parent classes. If you still want tocall them, you can prefix them with. (like thesuper keywordin other languages):
funcsome_func(x):.some_func(x)# Calls the same function on the parent class.
Note
Default functions like_init, and most notifications such as_enter_tree,_exit_tree,_process,_physics_process,etc. are called in all parent classes automatically.There is no need to call them explicitly when overloading them.
Class constructor¶
The class constructor, called on class instantiation, is named_init. Asmentioned earlier, the constructors of parent classes are called automaticallywhen inheriting a class. So, there is usually no need to call._init()explicitly.
Unlike the call of a regular function, like in the above example with.some_func, if the constructor from the inherited class takes arguments,they are passed like this:
func_init(args).(parent_args):pass
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).(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_initconstructor that takesarguments (ein this case), then the inheriting class (Idle.gd)mustdefine_initas well and pass appropriate parameters to_initfromState.gd.Idle.gdcan have a different number of arguments than the parent classState.gd.In the example above,
epassed to theState.gdconstructor is the sameepassedin toIdle.gd.If
Idle.gd's_initconstructor takes 0 arguments, it still needs to pass some valueto theState.gdparent class, even if it does nothing. This brings us to the fact that youcan pass literals in the base constructor as well, not just variables, e.g.:# Idle.gdfunc_init().(5):pass
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 asresources. 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 exports.
Setters/getters¶
It is often useful to know when a class' member variable changes forwhatever reason. It may also be desired to encapsulate its access in some way.
For this, GDScript provides asetter/getter syntax using thesetget keyword.It is used directly after a variable definition:
varvariable=valuesetgetsetterfunc,getterfunc
Whenever the value ofvariable is modified by anexternal source(i.e. not from local usage in the class), thesetter function (setterfunc above)will be called. This happensbefore the value is changed. Thesetter must decide what to dowith the new value. Vice versa, whenvariable is accessed, thegetter function(getterfunc above) mustreturn the desired value. Below is an example:
varmy_varsetgetmy_var_set,my_var_getfuncmy_var_set(new_value):my_var=new_valuefuncmy_var_get():returnmy_var# Getter must return a value.
Either of thesetter orgetter functions can be omitted:
# Only a setter.varmy_var=5setgetmy_var_set# Only a getter (note the comma).varmy_var=5setget,my_var_get
Setters and getters are useful whenexporting variablesto the editor in tool scripts or plugins, for validating input.
As said,local access willnot trigger the setter and getter. Here is anillustration of this:
func_init():# Does not trigger setter/getter.my_integer=5print(my_integer)# Does trigger setter/getter.self.my_integer=5print(self.my_integer)
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, thetool keyword 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¶
If a class inherits fromReference, then instances will befreed when no longer in use. No garbage collector exists, justreference counting. By default, all classes that don't defineinheritance extendReference. If this is not desired, then a classmust inheritObject manually and must callinstance.free(). Toavoid reference cycles that can't be freed, aWeakRef function isprovided for creating weak references. Here is an example:
extendsNodevarmy_node_reffunc_ready():my_node_ref=weakref(get_node("MyNode"))func_this_is_called_later():varmy_node=my_node_ref.get_ref()ifmy_node:my_node.do_something()
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 orRigidBody.
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.connect("health_depleted",self,"_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 withObject.emit_signal(), and fromaGame node higher up our scene tree, we connect it to theLifebar usingtheObject.connect() method:
# Character.gd...signalhealth_changedfunctake_damage(amount):varold_health=healthhealth-=amount# We emit the health_changed signal every time the# character takes damage.emit_signal("health_changed",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)...
Note
To use signals, your class has to extend theObject class or anytype extending it likeNode,KinematicBody,Control...
In theGame node, we get both theCharacter andLifebar nodes, thenconnect the character, that emits the signal, to the receiver, theLifebarnode in this case.
# Game.gdfunc_ready():varcharacter_node=get_node('Character')varlifebar_node=get_node('UserInterface/Lifebar')character_node.connect("health_changed",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.

GDScript can bind an array of values to connections between a signaland a method. When the signal is emitted, the callback method receivesthe 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 theconnection if the emitted signal itself doesn't give you access to all the datathat you need.
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 in the binds array argument:
# Game.gdfunc_ready():varcharacter_node=get_node('Character')varbattle_log_node=get_node('UserInterface/BattleLog')character_node.connect("health_changed",battle_log_node,"_on_Character_health_changed",[character_node.name])
OurBattleLog node receives each element in the binds array as an extra argument:
# BattleLog.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."
Coroutines with yield¶
GDScript offers support forcoroutinesvia theyield built-in function. Callingyield() willimmediately return from the current function, with the current frozenstate of the same function as the return value. Callingresume() onthis resulting object will continue execution and return whatever thefunction returns. Once resumed, the state object becomes invalid. Here isan example:
funcmy_func():print("Hello")yield()print("world")func_ready():vary=my_func()# Function state saved in 'y'.print("my dear")y.resume()# 'y' resumed and is now an invalid state.
Will print:
Hellomydearworld
It is also possible to pass values betweenyield() andresume(),for example:
funcmy_func():print("Hello")print(yield())return"cheers!"func_ready():vary=my_func()# Function state saved in 'y'.print(y.resume("world"))# 'y' resumed and is now an invalid state.
Will print:
Helloworldcheers!
Remember to save the new function state, when using multipleyields:
funcco_func():foriinrange(1,5):print("Turn%d"%i)yield();func_ready():varco=co_func();whilecoisGDScriptFunctionState&&co.is_valid():co=co.resume();
Coroutines & signals¶
The real strength of usingyield is when combined with signals.yield can accept two arguments, an object and a signal. When thesignal is received, execution will recommence. Here are some examples:
# Resume execution the next frame.yield(get_tree(),"idle_frame")# Resume execution when animation is done playing.yield(get_node("AnimationPlayer"),"animation_finished")# Wait 5 seconds, then resume execution.yield(get_tree().create_timer(5.0),"timeout")
Coroutines themselves use thecompleted signal when they transitioninto an invalid state, for example:
funcmy_func():yield(button_func(),"completed")print("All buttons were pressed, hurray!")funcbutton_func():yield($Button0,"pressed")yield($Button1,"pressed")
my_func will only continue execution once both buttons have been pressed.
You can also get the signal's argument once it's emitted by an object:
# Wait for when any node is added to the scene tree.varnode=yield(get_tree(),"node_added")
If there is more than one argument,yield returns an array containingthe arguments:
signaldone(input,processed)funcprocess_input(input):print("Processing initialized")yield(get_tree(),"idle_frame")print("Waiting")yield(get_tree(),"idle_frame")emit_signal("done",input,"Processed "+input)func_ready():process_input("Test")# Prints: Processing initializedvardata=yield(self,"done")# Prints: waitingprint(data[1])# Prints: Processed Test
If you're unsure whether a function may yield or not, or whether it may yieldmultiple times, you can yield to thecompleted signal conditionally:
funcgenerate():varresult=rand_range(-1.0,1.0)ifresult<0.0:yield(get_tree(),"idle_frame")returnresultfuncmake():varresult=generate()ifresultisGDScriptFunctionState:# Still working.result=yield(result,"completed")returnresult
This ensures that the function returns whatever it was supposed to returnregardless of whether coroutines were used internally. Note that usingwhile would be redundant here as thecompleted signal is only emittedwhen the function didn't yield anymore.
onready keyword¶
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 theonready keyword, thatdefers initialization of a member variable until_ready() is called. Itcan replace the above code with a single line:
onreadyvarmy_label=get_node("MyLabel")
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.