Object¶
Inherited By: AudioServer, CameraServer, ClassDB, DisplayServer, EditorFileSystemDirectory, EditorPaths, EditorSelection, EditorVCSInterface, Engine, EngineDebugger, Geometry2D, Geometry3D, GodotSharp, IP, Input, InputMap, JNISingleton, JSONRPC, JavaClassWrapper, JavaScript, MainLoop, Marshalls, MovieWriter, NativeExtensionManager, NavigationMeshGenerator, NavigationServer2D, NavigationServer3D, Node, OS, Performance, PhysicsDirectBodyState2D, PhysicsDirectBodyState3D, PhysicsDirectSpaceState2D, PhysicsDirectSpaceState3D, PhysicsServer2D, PhysicsServer3D, PhysicsServer3DRenderingServerHandler, ProjectSettings, RefCounted, RenderingDevice, RenderingServer, ResourceLoader, ResourceSaver, ResourceUID, ScriptLanguage, TextServerManager, TileData, Time, TranslationServer, TreeItem, UndoRedo, VisualScriptCustomNodes, XRServer
Base class for all non-built-in types.
Description¶
Every class which is not a built-in type inherits from this class.
You can construct Objects from scripting languages, using Object.new()
in GDScript, new Object
in C#, or the "Construct Object" node in VisualScript.
Objects do not manage memory. If a class inherits from Object, you will have to delete instances of it manually. To do so, call the free method from your script or delete the instance from C++.
Some classes that extend Object add memory management. This is the case of RefCounted, which counts references and deletes itself automatically when no longer referenced. Node, another fundamental type, deletes all its children when freed from memory.
Objects export properties, which are mainly useful for storage and editing, but not really so much in programming. Properties are exported in _get_property_list and handled in _get and _set. However, scripting languages and C++ have simpler means to export them.
Property membership can be tested directly in GDScript using in
:
var n = Node2D.new()
print("position" in n) # Prints "true".
print("other_property" in n) # Prints "false".
var node = new Node2D();
// C# has no direct equivalent to GDScript's `in` operator here, but we
// can achieve the same behavior by performing `Get` with a null check.
GD.Print(node.Get("position") != null); // Prints "true".
GD.Print(node.Get("other_property") != null); // Prints "false".
The in
operator will evaluate to true
as long as the key exists, even if the value is null
.
Objects also receive notifications. Notifications are a simple way to notify the object about different events, so they can all be handled together. See _notification.
Note: Unlike references to a RefCounted, references to an Object stored in a variable can become invalid without warning. Therefore, it's recommended to use RefCounted for data classes instead of Object
.
Note: The script
property is not exposed like most properties, but it does have a setter and getter (set_script()
and get_script()
).
Tutorials¶
Methods¶
_get ( StringName property ) virtual |
|
_get_property_list ( ) virtual |
|
void |
_init ( ) virtual |
void |
_notification ( int what ) virtual |
_set ( StringName property, Variant value ) virtual |
|
_to_string ( ) virtual |
|
void |
add_user_signal ( String signal, Array arguments=[] ) |
call ( StringName method, ... ) vararg |
|
call_deferred ( StringName method, ... ) vararg |
|
callv ( StringName method, Array arg_array ) |
|
can_translate_messages ( ) const |
|
connect ( StringName signal, Callable callable, Array binds=[], int flags=0 ) |
|
void |
disconnect ( StringName signal, Callable callable ) |
emit_signal ( StringName signal, ... ) vararg |
|
void |
free ( ) |
get ( StringName property ) const |
|
get_class ( ) const |
|
get_incoming_connections ( ) const |
|
get_indexed ( NodePath property ) const |
|
get_instance_id ( ) const |
|
get_meta ( StringName name, Variant default=null ) const |
|
get_meta_list ( ) const |
|
get_method_list ( ) const |
|
get_property_list ( ) const |
|
get_script ( ) const |
|
get_signal_connection_list ( StringName signal ) const |
|
get_signal_list ( ) const |
|
has_meta ( StringName name ) const |
|
has_method ( StringName method ) const |
|
has_signal ( StringName signal ) const |
|
has_user_signal ( StringName signal ) const |
|
is_blocking_signals ( ) const |
|
is_connected ( StringName signal, Callable callable ) const |
|
is_queued_for_deletion ( ) const |
|
void |
notification ( int what, bool reversed=false ) |
void |
|
void |
remove_meta ( StringName name ) |
void |
set ( StringName property, Variant value ) |
void |
set_block_signals ( bool enable ) |
void |
set_deferred ( StringName property, Variant value ) |
void |
set_indexed ( NodePath property, Variant value ) |
void |
set_message_translation ( bool enable ) |
void |
set_meta ( StringName name, Variant value ) |
void |
set_script ( Variant script ) |
to_string ( ) |
|
tr ( StringName message, StringName context="" ) const |
|
tr_n ( StringName message, StringName plural_message, int n, StringName context="" ) const |
Signals¶
property_list_changed ( )
script_changed ( )
Emitted whenever the object's script is changed.
Enumerations¶
enum ConnectFlags:
CONNECT_DEFERRED = 1 --- Connects a signal in deferred mode. This way, signal emissions are stored in a queue, then set on idle time.
CONNECT_PERSIST = 2 --- Persisting connections are saved when the object is serialized to file.
CONNECT_ONESHOT = 4 --- One-shot connections disconnect themselves after emission.
CONNECT_REFERENCE_COUNTED = 8 --- Connect a signal as reference-counted. This means that a given signal can be connected several times to the same target, and will only be fully disconnected once no references are left.
Constants¶
NOTIFICATION_POSTINITIALIZE = 0 --- Called right when the object is initialized. Not available in script.
NOTIFICATION_PREDELETE = 1 --- Called before the object is about to be deleted.
Method Descriptions¶
Variant _get ( StringName property ) virtual
Virtual method which can be overridden to customize the return value of get.
Returns the given property. Returns null
if the property
does not exist.
Array _get_property_list ( ) virtual
Virtual method which can be overridden to customize the return value of get_property_list.
Returns the object's property list as an Array of dictionaries.
Each property's Dictionary must contain at least name: String
and type: int
(see Variant.Type) entries. Optionally, it can also include hint: int
(see PropertyHint), hint_string: String
, and usage: int
(see PropertyUsageFlags).
void _init ( ) virtual
Called when the object is initialized in memory. Can be defined to take in parameters, that are passed in when constructing.
Note: If _init is defined with required parameters, then explicit construction is the only valid means of creating an Object of the class. If any other means (such as PackedScene.instantiate) is used, then initialization will fail.
void _notification ( int what ) virtual
Called whenever the object receives a notification, which is identified in what
by a constant. The base Object
has two constants NOTIFICATION_POSTINITIALIZE and NOTIFICATION_PREDELETE, but subclasses such as Node define a lot more notifications which are also received by this method.
bool _set ( StringName property, Variant value ) virtual
Virtual method which can be overridden to customize the return value of set.
Sets a property. Returns true
if the property
exists.
String _to_string ( ) virtual
Virtual method which can be overridden to customize the return value of to_string, and thus the object's representation where it is converted to a string, e.g. with print(obj)
.
Returns a String representing the object. If not overridden, defaults to "[ClassName:RID]"
.
Adds a user-defined signal
. Arguments are optional, but can be added as an Array of dictionaries, each containing name: String
and type: int
(see Variant.Type) entries.
Variant call ( StringName method, ... ) vararg
Calls the method
on the object and returns the result. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:
var node = Node3D.new()
node.call("rotate", Vector3(1.0, 0.0, 0.0), 1.571)
var node = new Node3D();
node.Call("rotate", new Vector3(1f, 0f, 0f), 1.571f);
Note: In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase).
Variant call_deferred ( StringName method, ... ) vararg
Calls the method
on the object during idle time. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:
var node = Node3D.new()
node.call_deferred("rotate", Vector3(1.0, 0.0, 0.0), 1.571)
var node = new Node3D();
node.CallDeferred("rotate", new Vector3(1f, 0f, 0f), 1.571f);
Note: In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase).
Variant callv ( StringName method, Array arg_array )
Calls the method
on the object and returns the result. Contrarily to call, this method does not support a variable number of arguments but expects all parameters to be via a single Array.
var node = Node3D.new()
node.callv("rotate", [Vector3(1.0, 0.0, 0.0), 1.571])
var node = new Node3D();
node.Callv("rotate", new Godot.Collections.Array { new Vector3(1f, 0f, 0f), 1.571f });
bool can_translate_messages ( ) const
Returns true
if the object can translate strings. See set_message_translation and tr.
Error connect ( StringName signal, Callable callable, Array binds=[], int flags=0 )
Connects a signal
to a callable
. Pass optional binds
to the call as an Array of parameters. These parameters will be passed to the Callable's method after any parameter used in the call to emit_signal. Use flags
to set deferred or one-shot connections. See ConnectFlags constants.
Note: This method is the legacy implementation for connecting signals. The recommended modern approach is to use Signal.connect and to use Callable.bind to add and validate parameter binds. Both syntaxes are shown below.
A signal can only be connected once to a Callable. It will print an error if already connected, unless the signal was connected with CONNECT_REFERENCE_COUNTED. To avoid this, first, use is_connected to check for existing connections.
If the callable's target is destroyed in the game's lifecycle, the connection will be lost.
Examples with recommended syntax:
Connecting signals is one of the most common operations in Godot and the API gives many options to do so, which are described further down. The code block below shows the recommended approach for both GDScript and C#.
func _ready():
var button = Button.new()
# `button_down` here is a Signal object, and we thus call the Signal.connect() method,
# not Object.connect(). See discussion below for a more in-depth overview of the API.
button.button_down.connect(_on_button_down)
# This assumes that a `Player` class exists which defines a `hit` signal.
var player = Player.new()
# We use Signal.connect() again, and we also use the Callable.bind() method which
# returns a new Callable with the parameter binds.
player.hit.connect(_on_player_hit.bind("sword", 100))
func _on_button_down():
print("Button down!")
func _on_player_hit(weapon_type, damage):
print("Hit with weapon %s for %d damage." % [weapon_type, damage])
public override void _Ready()
{
var button = new Button();
// C# supports passing signals as events, so we can use this idiomatic construct:
button.ButtonDown += OnButtonDown;
// This assumes that a `Player` class exists which defines a `Hit` signal.
var player = new Player();
// Signals as events (`player.Hit += OnPlayerHit;`) do not support argument binding. You have to use:
player.Hit.Connect(OnPlayerHit, new Godot.Collections.Array {"sword", 100 });
}
private void OnButtonDown()
{
GD.Print("Button down!");
}
private void OnPlayerHit(string weaponType, int damage)
{
GD.Print(String.Format("Hit with weapon {0} for {1} damage.", weaponType, damage));
}
``Object.connect()`` or ``Signal.connect()``?
As seen above, the recommended method to connect signals is not connect. The code block below shows the four options for connecting signals, using either this legacy method or the recommended Signal.connect, and using either an implicit Callable or a manually defined one.
func _ready():
var button = Button.new()
# Option 1: Object.connect() with an implicit Callable for the defined function.
button.connect("button_down", _on_button_down)
# Option 2: Object.connect() with a constructed Callable using a target object and method name.
button.connect("button_down", Callable(self, "_on_button_down"))
# Option 3: Signal.connect() with an implicit Callable for the defined function.
button.button_down.connect(_on_button_down)
# Option 4: Signal.connect() with a constructed Callable using a target object and method name.
button.button_down.connect(Callable(self, "_on_button_down"))
func _on_button_down():
print("Button down!")
public override void _Ready()
{
var button = new Button();
// Option 1: Object.Connect() with an implicit Callable for the defined function.
button.Connect("button_down", OnButtonDown);
// Option 2: Object.connect() with a constructed Callable using a target object and method name.
button.Connect("button_down", new Callable(self, nameof(OnButtonDown)));
// Option 3: Signal.connect() with an implicit Callable for the defined function.
button.ButtonDown.Connect(OnButtonDown);
// Option 3b: In C#, we can use signals as events and connect with this more idiomatic syntax:
button.ButtonDown += OnButtonDown;
// Option 4: Signal.connect() with a constructed Callable using a target object and method name.
button.ButtonDown.Connect(new Callable(self, nameof(OnButtonDown)));
}
private void OnButtonDown()
{
GD.Print("Button down!");
}
While all options have the same outcome (button
's BaseButton.button_down signal will be connected to _on_button_down
), option 3 offers the best validation: it will print a compile-time error if either the button_down
signal or the _on_button_down
callable are undefined. On the other hand, option 2 only relies on string names and will only be able to validate either names at runtime: it will print a runtime error if "button_down"
doesn't correspond to a signal, or if "_on_button_down"
is not a registered method in the object self
. The main reason for using options 1, 2, or 4 would be if you actually need to use strings (e.g. to connect signals programmatically based on strings read from a configuration file). Otherwise, option 3 is the recommended (and fastest) method.
Parameter bindings and passing:
For legacy or language-specific reasons, there are also several ways to bind parameters to signals. One can pass a binds
Array to connect or Signal.connect, or use the recommended Callable.bind method to create a new callable from an existing one, with the given parameter binds.
One can also pass additional parameters when emitting the signal with emit_signal. The examples below show the relationship between those two types of parameters.
func _ready():
# This assumes that a `Player` class exists which defines a `hit` signal.
var player = Player.new()
# Option 1: Using Callable.bind().
player.hit.connect(_on_player_hit.bind("sword", 100))
# Option 2: Using a `binds` Array in Signal.connect() (same syntax for Object.connect()).
player.hit.connect(_on_player_hit, ["sword", 100])
# Parameters added when emitting the signal are passed first.
player.emit_signal("hit", "Dark lord", 5)
# Four arguments, since we pass two when emitting (hit_by, level)
# and two when connecting (weapon_type, damage).
func _on_player_hit(hit_by, level, weapon_type, damage):
print("Hit by %s (level %d) with weapon %s for %d damage." % [hit_by, level, weapon_type, damage])
public override void _Ready()
{
// This assumes that a `Player` class exists which defines a `Hit` signal.
var player = new Player();
// Option 1: Using Callable.Bind(). This way we can still use signals as events.
player.Hit += OnPlayerHit.Bind("sword", 100);
// Option 2: Using a `binds` Array in Signal.Connect() (same syntax for Object.Connect()).
player.Hit.Connect(OnPlayerHit, new Godot.Collections.Array{ "sword", 100 });
// Parameters added when emitting the signal are passed first.
player.EmitSignal("hit", "Dark lord", 5);
}
// Four arguments, since we pass two when emitting (hitBy, level)
// and two when connecting (weaponType, damage).
private void OnPlayerHit(string hitBy, int level, string weaponType, int damage)
{
GD.Print(String.Format("Hit by {0} (level {1}) with weapon {2} for {3} damage.", hitBy, level, weaponType, damage));
}
void disconnect ( StringName signal, Callable callable )
Disconnects a signal
from a given callable
.
If you try to disconnect a connection that does not exist, the method will print an error. Use is_connected to ensure that the connection exists.
Error emit_signal ( StringName signal, ... ) vararg
Emits the given signal
. The signal must exist, so it should be a built-in signal of this class or one of its parent classes, or a user-defined signal. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:
emit_signal("hit", "sword", 100)
emit_signal("game_over")
EmitSignal("hit", "sword", 100);
EmitSignal("game_over");
void free ( )
Deletes the object from memory. Any pre-existing reference to the freed object will become invalid, e.g. is_instance_valid(object)
will return false
.
Variant get ( StringName property ) const
Returns the Variant value of the given property
. If the property
doesn't exist, this will return null
.
Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase).
String get_class ( ) const
Returns the object's class as a String. See also is_class.
Note: get_class does not take class_name
declarations into account. If the object has a class_name
defined, the base class name will be returned instead.
Array get_incoming_connections ( ) const
Returns an Array of dictionaries with information about signals that are connected to the object.
Each Dictionary contains three String entries:
source
is a reference to the signal emitter.signal_name
is the name of the connected signal.method_name
is the name of the method to which the signal is connected.
Gets the object's property indexed by the given NodePath. The node path should be relative to the current object and can use the colon character (:
) to access nested properties. Examples: "position:x"
or "material:next_pass:blend_mode"
.
Note: Even though the method takes NodePath argument, it doesn't support actual paths to Nodes in the scene tree, only colon-separated sub-property paths. For the purpose of nodes, use Node.get_node_and_resource instead.
int get_instance_id ( ) const
Returns the object's unique instance ID.
This ID can be saved in EncodedObjectAsID, and can be used to retrieve the object instance with @GlobalScope.instance_from_id.
Variant get_meta ( StringName name, Variant default=null ) const
Returns the object's metadata entry for the given name
.
Throws error if the entry does not exist, unless default
is not null
(in which case the default value will be returned).
PackedStringArray get_meta_list ( ) const
Returns the object's metadata as a PackedStringArray.
Array get_method_list ( ) const
Returns the object's methods and their signatures as an Array.
Array get_property_list ( ) const
Returns the object's property list as an Array of dictionaries.
Each property's Dictionary contain at least name: String
and type: int
(see Variant.Type) entries. Optionally, it can also include hint: int
(see PropertyHint), hint_string: String
, and usage: int
(see PropertyUsageFlags).
Variant get_script ( ) const
Returns the object's Script instance, or null
if none is assigned.
Array get_signal_connection_list ( StringName signal ) const
Returns an Array of connections for the given signal
.
Array get_signal_list ( ) const
Returns the list of signals as an Array of dictionaries.
bool has_meta ( StringName name ) const
Returns true
if a metadata entry is found with the given name
.
bool has_method ( StringName method ) const
Returns true
if the object contains the given method
.
bool has_signal ( StringName signal ) const
Returns true
if the given signal
exists.
bool has_user_signal ( StringName signal ) const
Returns true
if the given user-defined signal
exists. Only signals added using add_user_signal are taken into account.
bool is_blocking_signals ( ) const
Returns true
if signal emission blocking is enabled.
Returns true
if the object inherits from the given class
. See also get_class.
Note: is_class does not take class_name
declarations into account. If the object has a class_name
defined, is_class will return false
for that name.
bool is_connected ( StringName signal, Callable callable ) const
Returns true
if a connection exists for a given signal
and callable
.
bool is_queued_for_deletion ( ) const
Returns true
if the Node.queue_free method was called for the object.
Send a given notification to the object, which will also trigger a call to the _notification method of all classes that the object inherits from.
If reversed
is true
, _notification is called first on the object's own class, and then up to its successive parent classes. If reversed
is false
, _notification is called first on the highest ancestor (Object
itself), and then down to its successive inheriting classes.
void notify_property_list_changed ( )
Notify the editor that the property list has changed by emitting the property_list_changed signal, so that editor plugins can take the new values into account.
void remove_meta ( StringName name )
Removes a given entry from the object's metadata. See also set_meta.
void set ( StringName property, Variant value )
Assigns a new value to the given property. If the property
does not exist or the given value's type doesn't match, nothing will happen.
Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase).
void set_block_signals ( bool enable )
If set to true
, signal emission is blocked.
void set_deferred ( StringName property, Variant value )
Assigns a new value to the given property, after the current frame's physics step. This is equivalent to calling set via call_deferred, i.e. call_deferred("set", property, value)
.
Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase).
Assigns a new value to the property identified by the NodePath. The node path should be relative to the current object and can use the colon character (:
) to access nested properties. Example:
var node = Node2D.new()
node.set_indexed("position", Vector2(42, 0))
node.set_indexed("position:y", -10)
print(node.position) # (42, -10)
var node = new Node2D();
node.SetIndexed("position", new Vector2(42, 0));
node.SetIndexed("position:y", -10);
GD.Print(node.Position); // (42, -10)
void set_message_translation ( bool enable )
Defines whether the object can translate strings (with calls to tr). Enabled by default.
void set_meta ( StringName name, Variant value )
Adds, changes or removes a given entry in the object's metadata. Metadata are serialized and can take any Variant value.
To remove a given entry from the object's metadata, use remove_meta. Metadata is also removed if its value is set to null
. This means you can also use set_meta("name", null)
to remove metadata for "name"
.
void set_script ( Variant script )
Assigns a script to the object. Each object can have a single script assigned to it, which are used to extend its functionality.
If the object already had a script, the previous script instance will be freed and its variables and state will be lost. The new script's _init method will be called.
String to_string ( )
Returns a String representing the object. If not overridden, defaults to "[ClassName:RID]"
.
Override the method _to_string to customize the String representation.
String tr ( StringName message, StringName context="" ) const
Translates a message using translation catalogs configured in the Project Settings. An additional context could be used to specify the translation context.
Only works if message translation is enabled (which it is by default), otherwise it returns the message
unchanged. See set_message_translation.
See Internationalizing games for examples of the usage of this method.
String tr_n ( StringName message, StringName plural_message, int n, StringName context="" ) const
Translates a message involving plurals using translation catalogs configured in the Project Settings. An additional context could be used to specify the translation context.
Only works if message translation is enabled (which it is by default), otherwise it returns the message
or plural_message
unchanged. See set_message_translation.
The number n
is the number or quantity of the plural object. It will be used to guide the translation system to fetch the correct plural form for the selected language.
Note: Negative and floating-point values usually represent physical entities for which singular and plural don't clearly apply. In such cases, use tr.
See Localization using gettext for examples of the usage of this method.