You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
if# See "if/else/elif".elif# See "if/else/elif".else# See "if/else/elif".for# See "for".do# Reserved for future implementation of do…while loops.while# See "while".match# See "match".switch# Reserved for future implementation.case# Reserved for future implementation.break# Exits the execution of the current `for` or `while` loop.continue# Immediately skips to the next iteration of the `for` or `while` loop.pass# Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions.return# Returns a value from a function.class# Defines a class.extends# Defines what class to extend with the current class.is# Tests whether a variable extends a given class.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.
45# Base 10 integer0x8F51# Base 16 (hex) integer3.14, 58.1e-10# Floating point number (real)"Hello", 'Hi'# Strings"""Hello, Dude"""# Multiline string@"Node/Label"# NodePath or StringName
Comments
# This is a comment
Built-in types
Basic built-in types
null# empty data typebool# can only contain `true` or `false`int# can only contain integer numbers, (both negative and positive)float# used to contain a floating point valueString# a sequence of characters in Unicode format
Vector built-in types
Vector2# 2D vector type containing `x` and `y` fields. Rect2# 2D Rectangle type containing two vectors fields: `position` and `size`# Alternatively contains an `end` field which is `position+size`Vector3# 3D vector type containing x, y and z fieldsTransform2D# 3x2 matrix used for 2D transformsPlane# 3D Plane type in normalized form that contains # a normal vector field and a d scalar distanceQuat# Quaternion is a datatype used for representing a 3D rotationAABB# Axis-aligned bounding box (or 3D box) contains 2 vectors fields: `position` and `size`# Alternatively contains an `end` field which is `position+size`Basis# 3x3 matrix used for 3D rotation and scale
Engine built-in types
Color# Color data type contains r,g,b,a or h,s,v fields or HEX code.NodePath# Compiled path to a node used mainly in the scene systemRID# Resource ID (RID)Object# Base class for anything that is not a built-in type
Container built-in types
Arrays
vararr= []
arr= [1, 2, 3]
varb=arr[1] # this is 2varc=arr[arr.size() -1] # this is 3vard=arr[-1] # same as the previous line, but shorterarr[0] ="Hi!"# replacing value 1 with "Hi"arr.append(4) # array is now ["Hi", 2, 3, 4]
Array Types
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 of Vector2 objects.PoolVector3Array() # An array of Vector3 objects.PoolColorArray() # An array of Color objects.
vard= {} # create an empty Dictionaryd.waiting=14# add String "Waiting" as a key and assign the value 14 to itd[4] ="hello"# add integer `4` as a key and assign the String "hello" as its valued["Godot"] =3.01# add String "Godot" as a key and assign the value 3.01 to it# (4:hello), (Godot:3.01), (waiting:14)
Data
Variables
vara# data type is null by defaultvarb=5varc=3.8vard=b+c# variables are always initialized in order
Constants
consta=5constb=Vector2(20, 20)
constc=10+20# constant expressionconstd=Vector2(20, 30).x# constant expression: 20conste= [1, 2, 3, 4][0] # constant expression: 1constf=sin(20) # sin() can be used in constant expressionsconstg=x+20# invalid; this is not a constant expression!
Enums
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_IDLE=0constSTATE_JUMP=5constSTATE_SHOOT=6constState= {STATE_IDLE=0, STATE_JUMP=5, STATE_SHOOT=6}
Functions
funcmyfunction(a, b):
print(a)
print(b)
# return is optional; without it null is returnedreturna+b
Referencing Functions
# To call a function in a base class, prepend . to the function name:
.basefunc(args)
Static functions
staticfuncsum2(a, b):
returna+b
Statements and control flow
if/else/elif
if [expression]:
statement(s)
elif [expression]:
statement(s)
else:
statement(s)
# shortif1+1==2: return2+2else:
varx=3+3returnx# very shortvarx= [true-value] if [expression] else [false-value]
y+=3ify<10else-1
while
while [expression]:
statement(s)
for
forxin [5, 7, 11]:
statement# loop iterates 3 times with x as 5, then 7 and finally 11vardict= {"a": 0, "b": 1, "c": 2}
foriindict:
print(dict[i])
foriinrange(3):
statement# similar to [0, 1, 2] but does not allocate an arrayforiinrange(1,3):
statement# similar to [1, 2] but does not allocate an arrayforiinrange(2,8,2):
statement# similar to [2, 4, 6] but does not allocate an arrayforcin"Hello":
print(c) # iterate through all characters in a String, print every letter on new line
match
match [expression]:
[pattern](s):
[block]
[pattern](s):
[block]
[pattern](s):
[block]
constant pattern
matchx:
1:
print("We are number one!")
2:
print("Two are better than one!")
"test":
print("Oh snap! It's a string!")
matchx:
1:
print("it's one!")
2:
print("it's one times two!")
_:
print("it's not 1 or 2. I don't care tbh.")
binding
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
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
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")
# Inherit/extend a globally available classextendsSomeClass# Inherit/extend a named class fileextends"somefile.gd"# Inherit/extend an inner class in another fileextends"somefile.gd".SomeInnerClass
Check
# Cache the enemy classconstenemy_class=preload("enemy.gd")
# [...]# use 'is' to check inheritanceif (entityisenemy_class):
entity.apply_damage()
Class Constructor
func_init(args).(parent_args):
pass
Inner classes
# Inside a class file# An inner class in this class fileclassSomeInnerClass:
vara=5funcprint_value_of_a():
print(a)
# This is the constructor of the class file's main classfunc_init():
varc=SomeInnerClass.new()
c.print_value_of_a()
Classes as resources
# Load the class resource when calling load()varMyClass=load("myclass.gd")
# Preload the class only once at compile timevarMyClass2=preload("myclass.gd")
func_init():
vara=MyClass.new()
a.somefunction()
Exports
# If the exported value assigns a constant or constant expression,# the type will be inferred and used in the editorexportvarnumber=5# Export can take a basic data type as an argument which will be# used in the editorexport(int) varnumber# Export can also take a resource type to use as a hintexport(Texture) varcharacter_faceexport(PackedScene) varscene_file# Integers and strings hint enumerated values# Editor will enumerate as 0, 1 and 2export(int, "Warrior", "Magician", "Thief") varcharacter_class# Editor will enumerate with string namesexport(String, "Rebecca", "Mary", "Leah") varcharacter_name# Strings as paths# String is a path to a fileexport(String, FILE) varf# String is a path to a directoryexport(String, DIR) varf# String is a path to a file, custom filter provided as hintexport(String, FILE, "*.txt") varf# Using paths in the global filesystem is also possible,# but only in tool scripts (see further below)# String is a path to a PNG file in the global filesystemexport(String, FILE, GLOBAL, "*.png") vartool_image# String is a path to a directory in the global filesystemexport(String, DIR, GLOBAL) vartool_dir# The MULTILINE setting tells the editor to show a large input# field for editing over multiple linesexport(String, MULTILINE) vartext# Limiting editor input ranges# Allow integer values from 0 to 20export(int, 20) vari# Allow integer values from -10 to 20export(int, -10, 20) varj# Allow floats from -10 to 20, with a step of 0.2export(float, -10, 20, 0.2) vark# Allow values y = exp(x) where y varies between 100 and 1000# while snapping to steps of 20. The editor will present a# slider for easily editing the value.export(float, EXP, 100, 1000, 20) varl# Floats with easing hint# Display a visual representation of the ease() function# when editingexport(float, EASE) vartransition_speed# Colors# Color given as Red-Green-Blue valueexport(Color, RGB) varcol# Color is RGB# Color given as Red-Green-Blue-Alpha valueexport(Color, RGBA) varcol# Color is RGBA# Another node in the scene can be exported tooexport(NodePath) varnode# Exporting bit flags# Individually edit the bits of an integerexport(int, FLAGS) varspell_elements=ELEMENT_WIND|ELEMENT_WATER# Set any of the given flags from the editorexport(int, FLAGS, "Fire", "Water", "Earth", "Wind") varspell_elements=0# Exported array, shared between all instances.# Default value must be a constant expression.exportvara=[1,2,3]
# Typed arrays also work, only initialized empty:exportvarvector3s=PoolVector3Array()
exportvarstrings=PoolStringArray()
# Regular array, created local for every instance.# Default value can include run-time values, but can't# be exported.varb= [a,2,3]
Setters/getters
varmyvarsetgetmyvar_set,myvar_getfuncmyvar_set(newvalue):
myvar=newvaluefuncmyvar_get():
returnmyvar# getter must return a value
Tool mode
# Must restart GodottoolextendsButtonfunc_ready():
print("Hello")
Signals
# No argumentssignalyour_signal_name# With argumentssignalyour_signal_name_with_args(a,b)
func_callback_no_args():
print("Got callback!")
func_callback_args(a,b):
print("Got callback with args! a: ", a, " and b: ", b)
func_at_some_func():
instance.connect("your_signal_name", self, "_callback_no_args")
instance.connect("your_signal_name", self, "_callback_args", [22, "hello"])
instance.connect("your_signal_name_with_args", self, "_callback_args")
func_second_at_some_func():
emit_signal("your_signal_name")
emit_signal("your_signal_name_with_args", 55, 128)
someinstance.emit_signal("somesignal")
Coroutines
funcmyfunc():
print("hello")
yield()
print("world")
func_ready():
vary=myfunc()
# Function state saved in 'y'print("my dear")
y.resume()
# 'y' resumed and is now an invalid state#> hello#> my dear#> world
funcmyfunc():
print("hello")
print(yield())
return"cheers!"func_ready():
vary=myfunc()
# Function state saved in 'y'print(y.resume("world"))
# 'y' resumed and is now an invalid state#> hello#> world#> cheers!
Coroutines & signals
# Resume execution the next frameyield(get_tree(), "idle_frame")
# Resume execution when animation is done playing:yield(get_node("AnimationPlayer"), "finished")
# Wait 5 seconds, then resume executionyield(get_tree().create_timer(5.0), "timeout")
Onready keyword
varmylabelfunc_ready():
mylabel=get_node("MyLabel")
# Is the same as:onreadyvarmylabel=get_node("MyLabel")