Up to date

This page is up to date for Godot 4.0. If you still find outdated information, please open an issue.

@GDScript

Built-in GDScript constants, functions, and annotations.

Description

A list of GDScript-specific utility functions and annotations accessible from any script.

For the list of the global functions and constants see @GlobalScope.

Tutorials

Methods

Color

Color8 ( int r8, int g8, int b8, int a8=255 )

void

assert ( bool condition, String message=”” )

String

char ( int char )

Variant

convert ( Variant what, int type )

Object

dict_to_inst ( Dictionary dictionary )

Array

get_stack ( )

Dictionary

inst_to_dict ( Object instance )

bool

is_instance_of ( Variant value, Variant type )

int

len ( Variant var )

Resource

load ( String path )

Resource

preload ( String path )

void

print_debug () vararg

void

print_stack ( )

Array

range () vararg

bool

type_exists ( StringName type )


Constants

PI = 3.14159265358979

Constant that represents how many times the diameter of a circle fits around its perimeter. This is equivalent to TAU / 2, or 180 degrees in rotations.

TAU = 6.28318530717959

The circle constant, the circumference of the unit circle in radians. This is equivalent to PI * 2, or 360 degrees in rotations.

INF = inf

Positive floating-point infinity. This is the result of floating-point division when the divisor is 0.0. For negative infinity, use -INF. Dividing by -0.0 will result in negative infinity if the numerator is positive, so dividing by 0.0 is not the same as dividing by -0.0 (despite 0.0 == -0.0 returning true).

Warning: Numeric infinity is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer number by 0 will not result in INF and will result in a run-time error instead.

NAN = nan

“Not a Number”, an invalid floating-point value. NAN has special properties, including that != always returns true, while other comparison operators always return false. This is true even when comparing with itself (NAN == NAN returns false and NAN != NAN returns true). It is returned by some invalid operations, such as dividing floating-point 0.0 by 0.0.

Warning: “Not a Number” is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer 0 by 0 will not result in NAN and will result in a run-time error instead.


Annotations

@export ( )

Mark the following property as exported (editable in the Inspector dock and saved to disk). To control the type of the exported property, use the type hint notation.

  1. @export var string = ""
  2. @export var int_number = 5
  3. @export var float_number: float = 5
  4. @export var image: Image

@export_category ( String name )

Define a new category for the following exported properties. This helps to organize properties in the Inspector dock.

See also @GlobalScope.PROPERTY_USAGE_CATEGORY.

  1. @export_category("Statistics")
  2. @export var hp = 30
  3. @export var speed = 1.25

Note: Categories in the Inspector dock’s list usually divide properties coming from different classes (Node, Node2D, Sprite, etc.). For better clarity, it’s recommended to use @export_group and @export_subgroup, instead.


@export_color_no_alpha ( )

Export a Color property without allowing its transparency (Color.a) to be edited.

See also @GlobalScope.PROPERTY_HINT_COLOR_NO_ALPHA.

  1. @export_color_no_alpha var dye_color: Color

@export_dir ( )

Export a String property as a path to a directory. The path will be limited to the project folder and its subfolders. See @export_global_dir to allow picking from the entire filesystem.

See also @GlobalScope.PROPERTY_HINT_DIR.

  1. @export_dir var sprite_folder_path: String

@export_enum ( String names, … ) vararg

Export an int or String property as an enumerated list of options. If the property is an int, then the index of the value is stored, in the same order the values are provided. You can add explicit values using a colon. If the property is a String, then the value is stored.

See also @GlobalScope.PROPERTY_HINT_ENUM.

  1. @export_enum("Warrior", "Magician", "Thief") var character_class: int
  2. @export_enum("Slow:30", "Average:60", "Very Fast:200") var character_speed: int
  3. @export_enum("Rebecca", "Mary", "Leah") var character_name: String

If you want to set an initial value, you must specify it explicitly:

  1. @export_enum("Rebecca", "Mary", "Leah") var character_name: String = "Rebecca"

If you want to use named GDScript enums, then use @export instead:

  1. enum CharacterName {REBECCA, MARY, LEAH}
  2. @export var character_name: CharacterName

@export_exp_easing ( String hints=””, … ) vararg

Export a floating-point property with an easing editor widget. Additional hints can be provided to adjust the behavior of the widget. "attenuation" flips the curve, which makes it more intuitive for editing attenuation properties. "positive_only" limits values to only be greater than or equal to zero.

See also @GlobalScope.PROPERTY_HINT_EXP_EASING.

  1. @export_exp_easing var transition_speed
  2. @export_exp_easing("attenuation") var fading_attenuation
  3. @export_exp_easing("positive_only") var effect_power

@export_file ( String filter=””, … ) vararg

Export a String property as a path to a file. The path will be limited to the project folder and its subfolders. See @export_global_file to allow picking from the entire filesystem.

If filter is provided, only matching files will be available for picking.

See also @GlobalScope.PROPERTY_HINT_FILE.

  1. @export_file var sound_effect_path: String
  2. @export_file("*.txt") var notes_path: String

@export_flags ( String names, … ) vararg

Export an integer property as a bit flag field. This allows to store several “checked” or true values with one property, and comfortably select them from the Inspector dock.

See also @GlobalScope.PROPERTY_HINT_FLAGS.

  1. @export_flags("Fire", "Water", "Earth", "Wind") var spell_elements = 0

You can add explicit values using a colon:

  1. @export_flags("Self:4", "Allies:8", "Foes:16") var spell_targets = 0

You can also combine several flags:

  1. @export_flags("Self:4", "Allies:8", "Self and Allies:12", "Foes:16")
  2. var spell_targets = 0

Note: A flag value must be at least 1 and at most 2 ** 32 - 1.

Note: Unlike @export_enum, the previous explicit value is not taken into account. In the following example, A is 16, B is 2, C is 4.

  1. @export_flags("A:16", "B", "C") var x

@export_flags_2d_navigation ( )

Export an integer property as a bit flag field for 2D navigation layers. The widget in the Inspector dock will use the layer names defined in ProjectSettings.layer_names/2d_navigation/layer_1.

See also @GlobalScope.PROPERTY_HINT_LAYERS_2D_NAVIGATION.

  1. @export_flags_2d_navigation var navigation_layers: int

@export_flags_2d_physics ( )

Export an integer property as a bit flag field for 2D physics layers. The widget in the Inspector dock will use the layer names defined in ProjectSettings.layer_names/2d_physics/layer_1.

See also @GlobalScope.PROPERTY_HINT_LAYERS_2D_PHYSICS.

  1. @export_flags_2d_physics var physics_layers: int

@export_flags_2d_render ( )

Export an integer property as a bit flag field for 2D render layers. The widget in the Inspector dock will use the layer names defined in ProjectSettings.layer_names/2d_render/layer_1.

See also @GlobalScope.PROPERTY_HINT_LAYERS_2D_RENDER.

  1. @export_flags_2d_render var render_layers: int

@export_flags_3d_navigation ( )

Export an integer property as a bit flag field for 3D navigation layers. The widget in the Inspector dock will use the layer names defined in ProjectSettings.layer_names/3d_navigation/layer_1.

See also @GlobalScope.PROPERTY_HINT_LAYERS_3D_NAVIGATION.

  1. @export_flags_3d_navigation var navigation_layers: int

@export_flags_3d_physics ( )

Export an integer property as a bit flag field for 3D physics layers. The widget in the Inspector dock will use the layer names defined in ProjectSettings.layer_names/3d_physics/layer_1.

See also @GlobalScope.PROPERTY_HINT_LAYERS_3D_PHYSICS.

  1. @export_flags_3d_physics var physics_layers: int

@export_flags_3d_render ( )

Export an integer property as a bit flag field for 3D render layers. The widget in the Inspector dock will use the layer names defined in ProjectSettings.layer_names/3d_render/layer_1.

See also @GlobalScope.PROPERTY_HINT_LAYERS_3D_RENDER.

  1. @export_flags_3d_render var render_layers: int

@export_global_dir ( )

Export a String property as an absolute path to a directory. The path can be picked from the entire filesystem. See @export_dir to limit it to the project folder and its subfolders.

See also @GlobalScope.PROPERTY_HINT_GLOBAL_DIR.

  1. @export_global_dir var sprite_folder_path: String

@export_global_file ( String filter=””, … ) vararg

Export a String property as an absolute path to a file. The path can be picked from the entire filesystem. See @export_file to limit it to the project folder and its subfolders.

If filter is provided, only matching files will be available for picking.

See also @GlobalScope.PROPERTY_HINT_GLOBAL_FILE.

  1. @export_global_file var sound_effect_path: String
  2. @export_global_file("*.txt") var notes_path: String

@export_group ( String name, String prefix=”” )

Define a new group for the following exported properties. This helps to organize properties in the Inspector dock. Groups can be added with an optional prefix, which would make group to only consider properties that have this prefix. The grouping will break on the first property that doesn’t have a prefix. The prefix is also removed from the property’s name in the Inspector dock.

If no prefix is provided, then every following property will be added to the group. The group ends when then next group or category is defined. You can also force end a group by using this annotation with empty strings for parameters, @export_group("", "").

Groups cannot be nested, use @export_subgroup to add subgroups within groups.

See also @GlobalScope.PROPERTY_USAGE_GROUP.

  1. @export_group("Racer Properties")
  2. @export var nickname = "Nick"
  3. @export var age = 26
  4. @export_group("Car Properties", "car_")
  5. @export var car_label = "Speedy"
  6. @export var car_number = 3
  7. @export_group("", "")
  8. @export var ungrouped_number = 3

@export_multiline ( )

Export a String property with a large TextEdit widget instead of a LineEdit. This adds support for multiline content and makes it easier to edit large amount of text stored in the property.

See also @GlobalScope.PROPERTY_HINT_MULTILINE_TEXT.

  1. @export_multiline var character_biography

@export_node_path ( String type=””, … ) vararg

Export a NodePath property with a filter for allowed node types.

See also @GlobalScope.PROPERTY_HINT_NODE_PATH_VALID_TYPES.

  1. @export_node_path("Button", "TouchScreenButton") var some_button

@export_placeholder ( String placeholder )

Export a String property with a placeholder text displayed in the editor widget when no value is present.

See also @GlobalScope.PROPERTY_HINT_PLACEHOLDER_TEXT.

  1. @export_placeholder("Name in lowercase") var character_id: String

@export_range ( float min, float max, float step=1.0, String extra_hints=””, … ) vararg

Export an int or float property as a range value. The range must be defined by min and max, as well as an optional step and a variety of extra hints. The step defaults to 1 for integer properties. For floating-point numbers this value depends on your EditorSettings.interface/inspector/default_float_step setting.

If hints "or_greater" and "or_less" are provided, the editor widget will not cap the value at range boundaries. The "exp" hint will make the edited values on range to change exponentially. The "hide_slider" hint will hide the slider element of the editor widget.

Hints also allow to indicate the units for the edited value. Using "radians" you can specify that the actual value is in radians, but should be displayed in degrees in the Inspector dock. "degrees" allows to add a degree sign as a unit suffix. Finally, a custom suffix can be provided using "suffix:unit", where “unit” can be any string.

See also @GlobalScope.PROPERTY_HINT_RANGE.

  1. @export_range(0, 20) var number
  2. @export_range(-10, 20) var number
  3. @export_range(-10, 20, 0.2) var number: float
  4. @export_range(0, 100, 1, "or_greater") var power_percent
  5. @export_range(0, 100, 1, "or_greater", "or_less") var health_delta
  6. @export_range(-3.14, 3.14, 0.001, "radians") var angle_radians
  7. @export_range(0, 360, 1, "degrees") var angle_degrees
  8. @export_range(-8, 8, 2, "suffix:px") var target_offset

@export_subgroup ( String name, String prefix=”” )

Define a new subgroup for the following exported properties. This helps to organize properties in the Inspector dock. Subgroups work exactly like groups, except they need a parent group to exist. See @export_group.

See also @GlobalScope.PROPERTY_USAGE_SUBGROUP.

  1. @export_group("Racer Properties")
  2. @export var nickname = "Nick"
  3. @export var age = 26
  4. @export_subgroup("Car Properties", "car_")
  5. @export var car_label = "Speedy"
  6. @export var car_number = 3

Note: Subgroups cannot be nested, they only provide one extra level of depth. Just like the next group ends the previous group, so do the subsequent subgroups.


@icon ( String icon_path )

Add a custom icon to the current script. The script must be registered as a global class using the class_name keyword for this to have a visible effect. The icon specified at icon_path is displayed in the Scene dock for every node of that class, as well as in various editor dialogs.

  1. @icon("res://path/to/class/icon.svg")

Note: Only the script can have a custom icon. Inner classes are not supported.

Note: As annotations describe their subject, the @icon annotation must be placed before the class definition and inheritance.

Note: Unlike other annotations, the argument of the @icon annotation must be a string literal (constant expressions are not supported).


@onready ( )

Mark the following property as assigned when the Node is ready. Values for these properties are not assigned immediately when the node is initialized (Object._init), and instead are computed and stored right before Node._ready.

  1. @onready var character_name: Label = $Label

@rpc ( String mode=”authority”, String sync=”call_remote”, String transfer_mode=”unreliable”, int transfer_channel=0, … ) vararg

Mark the following method for remote procedure calls. See High-level multiplayer.

The order of mode, sync and transfer_mode does not matter and all arguments can be omitted, but transfer_channel always has to be the last argument. The accepted values for mode are "any_peer" or "authority", for sync are "call_remote" or "call_local" and for transfer_mode are "unreliable", "unreliable_ordered" or "reliable".

  1. @rpc
  2. func fn(): pass
  3. @rpc("any_peer", "unreliable_ordered")
  4. func fn_update_pos(): pass
  5. @rpc("authority", "call_remote", "unreliable", 0) # Equivalent to @rpc
  6. func fn_default(): pass

@tool ( )

Mark the current script as a tool script, allowing it to be loaded and executed by the editor. See Running code in the editor.

  1. @tool
  2. extends Node

Note: As annotations describe their subject, the @tool annotation must be placed before the class definition and inheritance.


@warning_ignore ( String warning, … ) vararg

Mark the following statement to ignore the specified warning. See GDScript warning system.

  1. func test():
  2. print("hello")
  3. return
  4. @warning_ignore("unreachable_code")
  5. print("unreachable")

Method Descriptions

Color Color8 ( int r8, int g8, int b8, int a8=255 )

Returns a Color constructed from red (r8), green (g8), blue (b8), and optionally alpha (a8) integer channels, each divided by 255.0 for their final value. Using Color8 instead of the standard Color constructor is useful when you need to match exact color values in an Image.

  1. var red = Color8(255, 0, 0) # Same as Color(1, 0, 0).
  2. var dark_blue = Color8(0, 0, 51) # Same as Color(0, 0, 0.2).
  3. var my_color = Color8(306, 255, 0, 102) # Same as Color(1.2, 1, 0, 0.4).

Note: Due to the lower precision of Color8 compared to the standard Color constructor, a color created with Color8 will generally not be equal to the same color created with the standard Color constructor. Use Color.is_equal_approx for comparisons to avoid issues with floating-point precision error.


void assert ( bool condition, String message=”” )

Asserts that the condition is true. If the condition is false, an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of @GlobalScope.push_error for reporting errors to project developers or add-on users.

An optional message can be shown in addition to the generic “Assertion failed” message. You can use this to provide additional details about why the assertion failed.

Warning: For performance reasons, the code inside assert is only executed in debug builds or when running the project from the editor. Don’t include code that has side effects in an assert call. Otherwise, the project will behave differently when exported in release mode.

  1. # Imagine we always want speed to be between 0 and 20.
  2. var speed = -10
  3. assert(speed < 20) # True, the program will continue.
  4. assert(speed >= 0) # False, the program will stop.
  5. assert(speed >= 0 and speed < 20) # You can also combine the two conditional statements in one check.
  6. assert(speed < 20, "the speed limit is 20") # Show a message.

String char ( int char )

Returns a single character (as a String) of the given Unicode code point (which is compatible with ASCII code).

  1. a = char(65) # a is "A"
  2. a = char(65 + 32) # a is "a"
  3. a = char(8364) # a is "€"

Variant convert ( Variant what, int type )

Converts what to type in the best way possible. The type uses the Variant.Type values.

  1. var a = [4, 2.5, 1.2]
  2. print(a is Array) # Prints true
  3. var b = convert(a, TYPE_PACKED_BYTE_ARRAY)
  4. print(b) # Prints [4, 2, 1]
  5. print(b is Array) # Prints false

Object dict_to_inst ( Dictionary dictionary )

Converts a dictionary (created with inst_to_dict) back to an Object instance. Can be useful for deserializing.


Array get_stack ( )

Returns an array of dictionaries representing the current call stack. See also print_stack.

  1. func _ready():
  2. foo()
  3. func foo():
  4. bar()
  5. func bar():
  6. print(get_stack())

Starting from _ready(), bar() would print:

  1. [{function:bar, line:12, source:res://script.gd}, {function:foo, line:9, source:res://script.gd}, {function:_ready, line:6, source:res://script.gd}]

Note: This function only works if the running instance is connected to a debugging server (i.e. an editor instance). get_stack will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server.

Note: Calling this function from a Thread is not supported. Doing so will return an empty array.


Dictionary inst_to_dict ( Object instance )

Returns the passed instance converted to a Dictionary. Can be useful for serializing.

Note: Cannot be used to serialize objects with built-in scripts attached or objects allocated within built-in scripts.

  1. var foo = "bar"
  2. func _ready():
  3. var d = inst_to_dict(self)
  4. print(d.keys())
  5. print(d.values())

Prints out:

  1. [@subpath, @path, foo]
  2. [, res://test.gd, bar]

bool is_instance_of ( Variant value, Variant type )

Returns true if value is an instance of type. The type value must be one of the following:

Unlike the right operand of the is operator, type can be a non-constant value. The is operator supports more features (such as typed arrays) and is more performant. Use the operator instead of this method if you do not need dynamic type checking.

Examples:

  1. print(is_instance_of(a, TYPE_INT))
  2. print(is_instance_of(a, Node))
  3. print(is_instance_of(a, MyClass))
  4. print(is_instance_of(a, MyClass.InnerClass))

Note: If value and/or type are freed objects (see @GlobalScope.is_instance_valid), or type is not one of the above options, this method will raise a runtime error.

See also @GlobalScope.typeof, type_exists, Array.is_same_typed (and other Array methods).


int len ( Variant var )

Returns the length of the given Variant var. The length can be the character count of a String, the element count of any array type or the size of a Dictionary. For every other Variant type, a run-time error is generated and execution is stopped.

  1. a = [1, 2, 3, 4]
  2. len(a) # Returns 4
  3. b = "Hello!"
  4. len(b) # Returns 6

Resource load ( String path )

Returns a Resource from the filesystem located at the absolute path. Unless it’s already referenced elsewhere (such as in another script or in the scene), the resource is loaded from disk on function call, which might cause a slight delay, especially when loading large scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use preload.

Note: Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing “Copy Path”, or by dragging the file from the FileSystem dock into the current script.

  1. # Load a scene called "main" located in the root of the project directory and cache it in a variable.
  2. var main = load("res://main.tscn") # main will contain a PackedScene resource.

Important: The path must be absolute. A relative path will always return null.

This function is a simplified version of ResourceLoader.load, which can be used for more advanced scenarios.

Note: Files have to be imported into the engine first to load them using this function. If you want to load Images at run-time, you may use Image.load. If you want to import audio files, you can use the snippet described in AudioStreamMP3.data.

Note: If ProjectSettings.editor/export/convert_text_resources_to_binary is true, load will not be able to read converted files in an exported project. If you rely on run-time loading of files present within the PCK, set ProjectSettings.editor/export/convert_text_resources_to_binary to false.


Resource preload ( String path )

Returns a Resource from the filesystem located at path. During run-time, the resource is loaded when the script is being parsed. This function effectively acts as a reference to that resource. Note that this function requires path to be a constant String. If you want to load a resource from a dynamic/variable path, use load.

Note: Resource paths can be obtained by right-clicking on a resource in the Assets Panel and choosing “Copy Path”, or by dragging the file from the FileSystem dock into the current script.

  1. # Create instance of a scene.
  2. var diamond = preload("res://diamond.tscn").instantiate()

void print_debug () vararg

Like @GlobalScope.print, but includes the current stack frame when running with the debugger turned on.

The output in the console may look like the following:

  1. Test print
  2. At: res://test.gd:15:_process()

Note: Calling this function from a Thread is not supported. Doing so will instead print the thread ID.


void print_stack ( )

Prints a stack trace at the current code location. See also get_stack.

The output in the console may look like the following:

  1. Frame 0 - res://test.gd:16 in function '_process'

Note: This function only works if the running instance is connected to a debugging server (i.e. an editor instance). print_stack will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server.

Note: Calling this function from a Thread is not supported. Doing so will instead print the thread ID.


Array range () vararg

Returns an array with the given range. range can be called in three ways:

range(n: int): Starts from 0, increases by steps of 1, and stops before n. The argument n is exclusive.

range(b: int, n: int): Starts from b, increases by steps of 1, and stops before n. The arguments b and n are inclusive and exclusive, respectively.

range(b: int, n: int, s: int): Starts from b, increases/decreases by steps of s, and stops before n. The arguments b and n are inclusive and exclusive, respectively. The argument s can be negative, but not 0. If s is 0, an error message is printed.

range converts all arguments to int before processing.

Note: Returns an empty array if no value meets the value constraint (e.g. range(2, 5, -1) or range(5, 5, 1)).

Examples:

  1. print(range(4)) # Prints [0, 1, 2, 3]
  2. print(range(2, 5)) # Prints [2, 3, 4]
  3. print(range(0, 6, 2)) # Prints [0, 2, 4]
  4. print(range(4, 1, -1)) # Prints [4, 3, 2]

To iterate over an Array backwards, use:

  1. var array = [3, 6, 9]
  2. for i in range(array.size(), 0, -1):
  3. print(array[i - 1])

Output:

  1. 9
  2. 6
  3. 3

To iterate over float, convert them in the loop.

  1. for i in range (3, 0, -1):
  2. print(i / 10.0)

Output:

  1. 0.3
  2. 0.2
  3. 0.1

bool type_exists ( StringName type )

Returns true if the given Object-derived class exists in ClassDB. Note that Variant data types are not registered in ClassDB.

  1. type_exists("Sprite2D") # Returns true
  2. type_exists("NonExistentClass") # Returns false