@GDScript

Built-in GDScript functions.

Description

A list of GDScript-specific utility functions accessed in 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 )

int

len ( Variant var )

Resource

load ( String path )

Resource

preload ( String path )

void

print_debug ( ... ) vararg

void

print_stack ( )

Array

range ( ... ) vararg

String

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

Note: 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 it is not equal to itself (NAN == NAN returns false). It is output by some invalid operations, such as dividing floating-point 0.0 by 0.0.

Note: "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.

@export var int_number = 5
@export var float_number: float = 5

  • @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.

@export_category("My Properties")
@export var number = 3
@export var string = ""

Note: Categories in the property list are supposed to indicate different base types, so the use of this annotation is not encouraged. See @export_group and @export_subgroup instead.


  • @export_color_no_alpha ( )

Export a Color property without an alpha (fixed as 1.0).

See also @GlobalScope.PROPERTY_HINT_COLOR_NO_ALPHA.

@export_color_no_alpha var modulate_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.

@export_dir var sprite_folder: String

  • @export_enum ( String names, ... ) vararg

Export a String or integer property as an enumerated list of options. If the property is an integer field, then the index of the value is stored, in the same order the values are provided. You can add specific identifiers for allowed values using a colon.

See also @GlobalScope.PROPERTY_HINT_ENUM.

@export_enum("Rebecca", "Mary", "Leah") var character_name: String
@export_enum("Warrior", "Magician", "Thief") var character_class: int
@export_enum("Walking:30", "Running:60", "Riding:200") var character_speed: int

  • @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.

@export_exp_easing var transition_speed
@export_exp_easing("attenuation") var fading_attenuation
@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.

@export_file var sound_effect_file: String
@export_file("*.txt") var notes_file: 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.

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

  • @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.

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

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

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

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

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

@export_flags_3d_render var render_layers: int

  • @export_global_dir ( )

Export a String property as a 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.

@export_global_dir var sprite_folder: String

  • @export_global_file ( String filter="", ... ) vararg

Export a String property as a 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.

@export_global_file var sound_effect_file: String
@export_global_file("*.txt") var notes_file: String

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, the every following property is 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 paramters, @export_group("", "").

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

See also @GlobalScope.PROPERTY_USAGE_GROUP.

@export_group("My Properties")
@export var number = 3
@export var string = ""

@export_group("Prefixed Properties", "prefix_")
@export var prefix_number = 3
@export var prefix_string = ""

@export_group("", "")
@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.

@export_multiline var character_bio

  • @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.

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

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

Export a numeric 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 "no_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.

@export_range(0, 20) var number
@export_range(-10, 20) var number
@export_range(-10, 20, 0.2) var number: float

@export_range(0, 100, 1, "or_greater") var power_percent
@export_range(0, 100, 1, "or_greater", "or_less") var health_delta

@export_range(-3.14, 3.14, 0.001, "radians") var angle_radians
@export_range(0, 360, 1, "degrees") var angle_degrees
@export_range(-8, 8, 2, "suffix:px") var target_offset

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.

@export_group("My Properties")
@export var number = 3
@export var string = ""

@export_subgroup("My Prefixed Properties", "prefix_")
@export var prefix_number = 3
@export var prefix_string = ""

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.


Add a custom icon to the current script. The icon is displayed in the Scene dock for every node that the script is attached to. For named classes the icon is also displayed in various editor dialogs.

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

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


  • @onready ( )

Mark the following property as assigned on Node's ready state change. Values for these properties are no assigned immediately upon the node's creation, and instead are computed and stored right before Node._ready.

@onready var character_name: Label = $Label

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

@rpc()

  • @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.

@tool
extends Node

  • @warning_ignore ( String warning, ... ) vararg

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

func test():
    print("hello")
    return
    @warning_ignore("unreachable_code")
    print("unreachable")

Method Descriptions

Returns a color constructed from integer red, green, blue, and alpha channels. Each channel should have 8 bits of information ranging from 0 to 255.

r8 red channel

g8 green channel

b8 blue channel

a8 alpha channel

red = Color8(255, 0, 0)

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

Note: 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.

The optional message argument, if given, is shown in addition to the generic "Assertion failed" message. It must be a static string, so format strings can't be used. You can use this to provide additional details about why the assertion failed.

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

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

a = char(65)      # a is "A"
a = char(65 + 32) # a is "a"
a = char(8364)    # a is "€"

Converts from a type to another in the best way possible. The type parameter uses the Variant.Type values.

a = Vector2(1, 0)
# Prints 1
print(a.length())
a = convert(a, TYPE_STRING)
# Prints 6 as "(1, 0)" is 6 characters
print(a.length())

Converts a dictionary (previously created with inst_to_dict) back to an Object instance. Useful for deserializing.


Returns an array of dictionaries representing the current call stack.

func _ready():
    foo()

func foo():
    bar()

func bar():
    print(get_stack())

would print

[{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: Not supported for calling from threads. Instead, this will return an empty array.


Returns the passed instance converted to a Dictionary (useful for serializing).

var foo = "bar"
func _ready():
    var d = inst_to_dict(self)
    print(d.keys())
    print(d.values())

Prints out:

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

Returns length of Variant var. Length is the character count of String, element count of Array, size of Dictionary, etc.

Note: Generates a fatal error if Variant can not provide a length.

a = [1, 2, 3, 4]
len(a) # Returns 4

Loads a resource from the filesystem located at path. The resource is loaded on the method call (unless it's referenced already elsewhere, e.g. in another script or in the scene), which might cause slight delay, especially when loading 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 script.

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

Important: The path must be absolute, a local path will just return null.

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

Note: You have to import the files into the engine first to load them using load. 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.


Returns a Resource from the filesystem located at path. The resource is loaded during script parsing, i.e. is loaded with the script and preload effectively acts as a reference to that resource. Note that the method requires a constant path. 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 script.

# Instance a scene.
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.

Output in the console would look something like this:

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

Note: Not supported for calling from threads. Instead of the stack frame, this will print the thread ID.


  • void print_stack ( )

Prints a stack trace at the current code location. Only works when running with debugger turned on.

Output in the console would look something like this:

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

Note: Not supported for calling from threads. Instead of the stack trace, this will 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:

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

To iterate over an Array backwards, use:

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

Output:

9
6
3

To iterate over float, convert them in the loop.

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

Output:

0.3
0.2
0.1

Converts one or more arguments to string in the best way possible.

var a = [10, 20, 30]
var b = str(a);
len(a) # Returns 3
len(b) # Returns 12

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

type_exists("Sprite2D") # Returns true
type_exists("NonExistentClass") # Returns false