Object
Inherited By:AudioServer,CameraServer,ClassDB,DisplayServer,EditorFileSystemDirectory,EditorInterface,EditorPaths,EditorSelection,EditorUndoRedoManager,EditorVCSInterface,Engine,EngineDebugger,FramebufferCacheRD,GDExtensionManager,Geometry2D,Geometry3D,Input,InputMap,IP,JavaClassWrapper,JavaScriptBridge,JNISingleton,JSONRPC,MainLoop,Marshalls,MovieWriter,NativeMenu,NavigationMeshGenerator,NavigationServer2D,NavigationServer3D,Node,OpenXRExtensionWrapperExtension,OpenXRInteractionProfileMetadata,OS,Performance,PhysicsDirectBodyState2D,PhysicsDirectBodyState3D,PhysicsDirectSpaceState2D,PhysicsDirectSpaceState3D,PhysicsServer2D,PhysicsServer2DManager,PhysicsServer3D,PhysicsServer3DManager,PhysicsServer3DRenderingServerHandler,ProjectSettings,RefCounted,RenderData,RenderingDevice,RenderingServer,RenderSceneData,ResourceLoader,ResourceSaver,ResourceUID,ScriptLanguage,ShaderIncludeDB,TextServerManager,ThemeDB,TileData,Time,TranslationServer,TreeItem,UndoRedo,UniformSetCacheRD,WorkerThreadPool,XRServer,XRVRS
Base class for all other classes in the engine.
Description
An advancedVariant type. All classes in the engine inherit from Object. Each class may define new properties, methods or signals, which are available to all inheriting classes. For example, aSprite2D instance is able to callNode.add_child() because it inherits fromNode.
You can create new instances, usingObject.new()
in GDScript, ornewGodotObject
in C#.
To delete an Object instance, callfree(). This is necessary for most classes inheriting Object, because they do not manage memory on their own, and will otherwise cause memory leaks when no longer in use. There are a few classes that perform memory management. For example,RefCounted (and by extensionResource) deletes itself when no longer referenced, andNode deletes its children when freed.
Objects can have aScript attached to them. Once theScript is instantiated, it effectively acts as an extension to the base class, allowing it to define and inherit new properties, methods and signals.
Inside aScript,_get_property_list() may be overridden to customize properties in several ways. This allows them to be available to the editor, display as lists of options, sub-divide into groups, save on disk, etc. Scripting languages offer easier ways to customize properties, such as with the@GDScript.@export annotation.
Godot is very dynamic. An object's script, and therefore its properties, methods and signals, can be changed at run-time. Because of this, there can be occasions where, for example, a property required by a method may not exist. To prevent run-time errors, see methods such asset(),get(),call(),has_method(),has_signal(), etc. Note that these methods aremuch slower than direct references.
In GDScript, you can also check if a given property, method, or signal name exists in an object with thein
operator:
varnode=Node.new()print("name"innode)# Prints trueprint("get_parent"innode)# Prints trueprint("tree_entered"innode)# Prints trueprint("unknown"innode)# Prints false
Notifications areint constants commonly sent and received by objects. For example, on every rendered frame, theSceneTree notifies nodes inside the tree with aNode.NOTIFICATION_PROCESS. The nodes receive it and may callNode._process() to update. To make use of notifications, seenotification() and_notification().
Lastly, every object can also contain metadata (data about data).set_meta() can be useful to store information that the object itself does not depend on. To keep your code clean, making excessive use of metadata is discouraged.
Note: Unlike references to aRefCounted, references to an object stored in a variable can become invalid without being set tonull
. To check if an object has been deleted, donot compare it againstnull
. Instead, use@GlobalScope.is_instance_valid(). It's also recommended to inherit fromRefCounted for classes storing data instead ofObject.
Note: Thescript
is not exposed like most properties. To set or get an object'sScript in code, useset_script() andget_script(), respectively.
Note: In a boolean context, anObject will evaluate tofalse
if it is equal tonull
or it has been freed. Otherwise, anObject will always evaluate totrue
. See also@GlobalScope.is_instance_valid().
Tutorials
Methods
Signals
property_list_changed()🔗
Emitted whennotify_property_list_changed() is called.
script_changed()🔗
Emitted when the object's script is changed.
Note: When this signal is emitted, the new script is not initialized yet. If you need to access the new script, defer connections to this signal withCONNECT_DEFERRED.
Enumerations
enumConnectFlags:🔗
ConnectFlagsCONNECT_DEFERRED =1
Deferred connections trigger theirCallables on idle time (at the end of the frame), rather than instantly.
ConnectFlagsCONNECT_PERSIST =2
Persisting connections are stored when the object is serialized (such as when usingPackedScene.pack()). In the editor, connections created through the Node dock are always persisting.
ConnectFlagsCONNECT_ONE_SHOT =4
One-shot connections disconnect themselves after emission.
ConnectFlagsCONNECT_REFERENCE_COUNTED =8
Reference-counted connections can be assigned to the sameCallable multiple times. Each disconnection decreases the internal counter. The signal fully disconnects only when the counter reaches 0.
Constants
NOTIFICATION_POSTINITIALIZE =0
🔗
Notification received when the object is initialized, before its script is attached. Used internally.
NOTIFICATION_PREDELETE =1
🔗
Notification received when the object is about to be deleted. Can be used like destructors in object-oriented programming languages.
NOTIFICATION_EXTENSION_RELOADED =2
🔗
Notification received when the object finishes hot reloading. This notification is only sent for extensions classes and derived.
Method Descriptions
Variant_get(property:StringName)virtual🔗
Override this method to customize the behavior ofget(). Should return the givenproperty
's value, ornull
if theproperty
should be handled normally.
Combined with_set() and_get_property_list(), this method allows defining custom properties, which is particularly useful for editor plugins. Note that a property must be present inget_property_list(), otherwise this method will not be called.
func_get(property):ifproperty=="fake_property":print("Getting my property!")return4func_get_property_list():return[{"name":"fake_property","type":TYPE_INT}]
publicoverrideVariant_Get(StringNameproperty){if(property=="FakeProperty"){GD.Print("Getting my property!");return4;}returndefault;}publicoverrideGodot.Collections.Array<Godot.Collections.Dictionary>_GetPropertyList(){return[ new Godot.Collections.Dictionary() { { "name", "FakeProperty" }, { "type", (int)Variant.Type.Int }, }, ];}
Array[Dictionary]_get_property_list()virtual🔗
Override this method to provide a custom list of additional properties to handle by the engine.
Should return a property list, as anArray of dictionaries. The result is added to the array ofget_property_list(), and should be formatted in the same way. EachDictionary must at least contain thename
andtype
entries.
You can use_property_can_revert() and_property_get_revert() to customize the default values of the properties added by this method.
The example below displays a list of numbers shown as words going fromZERO
toFIVE
, withnumber_count
controlling the size of the list:
@toolextendsNode@exportvarnumber_count=3:set(nc):number_count=ncnumbers.resize(number_count)notify_property_list_changed()varnumbers=PackedInt32Array([0,0,0])func_get_property_list():varproperties=[]foriinrange(number_count):properties.append({"name":"number_%d"%i,"type":TYPE_INT,"hint":PROPERTY_HINT_ENUM,"hint_string":"ZERO,ONE,TWO,THREE,FOUR,FIVE",})returnpropertiesfunc_get(property):ifproperty.begins_with("number_"):varindex=property.get_slice("_",1).to_int()returnnumbers[index]func_set(property,value):ifproperty.begins_with("number_"):varindex=property.get_slice("_",1).to_int()numbers[index]=valuereturntruereturnfalse
[Tool]publicpartialclassMyNode:Node{privateint_numberCount;[Export]publicintNumberCount{get=>_numberCount;set{_numberCount=value;_numbers.Resize(_numberCount);NotifyPropertyListChanged();}}privateGodot.Collections.Array<int>_numbers=[];publicoverrideGodot.Collections.Array<Godot.Collections.Dictionary>_GetPropertyList(){Godot.Collections.Array<Godot.Collections.Dictionary>properties=[];for(inti=0;i<_numberCount;i++){properties.Add(newGodot.Collections.Dictionary(){{"name",$"number_{i}"},{"type",(int)Variant.Type.Int},{"hint",(int)PropertyHint.Enum},{"hint_string","Zero,One,Two,Three,Four,Five"},});}returnproperties;}publicoverrideVariant_Get(StringNameproperty){stringpropertyName=property.ToString();if(propertyName.StartsWith("number_")){intindex=int.Parse(propertyName.Substring("number_".Length));return_numbers[index];}returndefault;}publicoverridebool_Set(StringNameproperty,Variantvalue){stringpropertyName=property.ToString();if(propertyName.StartsWith("number_")){intindex=int.Parse(propertyName.Substring("number_".Length));_numbers[index]=value.As<int>();returntrue;}returnfalse;}}
Note: This method is intended for advanced purposes. For most common use cases, the scripting languages offer easier ways to handle properties. See@GDScript.@export,@GDScript.@export_enum,@GDScript.@export_group, etc. If you want to customize exported properties, use_validate_property().
Note: If the object's script is not@GDScript.@tool, this method will not be called in the editor.
Called when the object's script is instantiated, oftentimes after the object is initialized in memory (throughObject.new()
in GDScript, ornewGodotObject
in C#). It can be also defined to take in parameters. This method is similar to a constructor in most programming languages.
Note: If_init() is defined withrequired parameters, the Object with script may only be created directly. If any other means (such asPackedScene.instantiate() orNode.duplicate()) are used, the script's initialization will fail.
Variant_iter_get(iter:Variant)virtual🔗
Returns the current iterable value.iter
stores the iteration state, but unlike_iter_init() and_iter_next() the state is supposed to be read-only, so there is noArray wrapper.
bool_iter_init(iter:Array)virtual🔗
Initializes the iterator.iter
stores the iteration state. Since GDScript does not support passing arguments by reference, a single-element array is used as a wrapper. Returnstrue
so long as the iterator has not reached the end.
Example:
classMyRange:var_fromvar_tofunc_init(from,to):assert(from<=to)_from=from_to=tofunc_iter_init(iter):iter[0]=_fromreturniter[0]<_tofunc_iter_next(iter):iter[0]+=1returniter[0]<_tofunc_iter_get(iter):returniterfunc_ready():varmy_range=MyRange.new(2,5)forxinmy_range:print(x)# Prints 2, 3, 4.
Note: Alternatively, you can ignoreiter
and use the object's state instead, seeonline docs for an example. Note that in this case you will not be able to reuse the same iterator instance in nested loops. Also, make sure you reset the iterator state in this method if you want to reuse the same instance multiple times.
bool_iter_next(iter:Array)virtual🔗
Moves the iterator to the next iteration.iter
stores the iteration state. Since GDScript does not support passing arguments by reference, a single-element array is used as a wrapper. Returnstrue
so long as the iterator has not reached the end.
void_notification(what:int)virtual🔗
Called when the object receives a notification, which can be identified inwhat
by comparing it with a constant. See alsonotification().
func_notification(what):ifwhat==NOTIFICATION_PREDELETE:print("Goodbye!")
publicoverridevoid_Notification(intwhat){if(what==NotificationPredelete){GD.Print("Goodbye!");}}
Note: The baseObject defines a few notifications (NOTIFICATION_POSTINITIALIZE andNOTIFICATION_PREDELETE). Inheriting classes such asNode define a lot more notifications, which are also received by this method.
bool_property_can_revert(property:StringName)virtual🔗
Override this method to customize the givenproperty
's revert behavior. Should returntrue
if theproperty
has a custom default value and is revertible in the Inspector dock. Use_property_get_revert() to specify theproperty
's default value.
Note: This method must return consistently, regardless of the current value of theproperty
.
Variant_property_get_revert(property:StringName)virtual🔗
Override this method to customize the givenproperty
's revert behavior. Should return the default value for theproperty
. If the default value differs from theproperty
's current value, a revert icon is displayed in the Inspector dock.
Note:_property_can_revert() must also be overridden for this method to be called.
bool_set(property:StringName, value:Variant)virtual🔗
Override this method to customize the behavior ofset(). Should set theproperty
tovalue
and returntrue
, orfalse
if theproperty
should be handled normally. Theexact way to set theproperty
is up to this method's implementation.
Combined with_get() and_get_property_list(), this method allows defining custom properties, which is particularly useful for editor plugins. Note that a propertymust be present inget_property_list(), otherwise this method will not be called.
varinternal_data={}func_set(property,value):ifproperty=="fake_property":# Storing the value in the fake property.internal_data["fake_property"]=valuereturntruereturnfalsefunc_get_property_list():return[{"name":"fake_property","type":TYPE_INT}]
privateGodot.Collections.Dictionary_internalData=newGodot.Collections.Dictionary();publicoverridebool_Set(StringNameproperty,Variantvalue){if(property=="FakeProperty"){// Storing the value in the fake property._internalData["FakeProperty"]=value;returntrue;}returnfalse;}publicoverrideGodot.Collections.Array<Godot.Collections.Dictionary>_GetPropertyList(){return[ new Godot.Collections.Dictionary() { { "name", "FakeProperty" }, { "type", (int)Variant.Type.Int }, }, ];}
Override this method to customize the return value ofto_string(), and therefore the object's representation as aString.
func_to_string():return"Welcome to Godot 4!"func_init():print(self)# Prints "Welcome to Godot 4!"vara=str(self)# a is "Welcome to Godot 4!"
void_validate_property(property:Dictionary)virtual🔗
Override this method to customize existing properties. Every property info goes through this method, except properties added with_get_property_list(). The dictionary contents is the same as in_get_property_list().
@toolextendsNode@exportvaris_number_editable:bool:set(value):is_number_editable=valuenotify_property_list_changed()@exportvarnumber:intfunc_validate_property(property:Dictionary):ifproperty.name=="number"andnotis_number_editable:property.usage|=PROPERTY_USAGE_READ_ONLY
[Tool]publicpartialclassMyNode:Node{privatebool_isNumberEditable;[Export]publicboolIsNumberEditable{get=>_isNumberEditable;set{_isNumberEditable=value;NotifyPropertyListChanged();}}[Export]publicintNumber{get;set;}publicoverridevoid_ValidateProperty(Godot.Collections.Dictionaryproperty){if(property["name"].AsStringName()==PropertyName.Number&&!IsNumberEditable){varusage=property["usage"].As<PropertyUsageFlags>()|PropertyUsageFlags.ReadOnly;property["usage"]=(int)usage;}}}
voidadd_user_signal(signal:String, arguments:Array = [])🔗
Adds a user-defined signal namedsignal
. Optional arguments for the signal can be added as anArray of dictionaries, each defining aname
String and atype
int (seeVariant.Type). See alsohas_user_signal() andremove_user_signal().
add_user_signal("hurt",[{"name":"damage","type":TYPE_INT},{"name":"source","type":TYPE_OBJECT}])
AddUserSignal("Hurt",[ new Godot.Collections.Dictionary() { { "name", "damage" }, { "type", (int)Variant.Type.Int }, }, new Godot.Collections.Dictionary() { { "name", "source" }, { "type", (int)Variant.Type.Object }, },]);
Variantcall(method:StringName, ...)vararg🔗
Calls themethod
on the object and returns the result. This method supports a variable number of arguments, so parameters can be passed as a comma separated list.
varnode=Node3D.new()node.call("rotate",Vector3(1.0,0.0,0.0),1.571)
varnode=newNode3D();node.Call(Node3D.MethodName.Rotate,newVector3(1f,0f,0f),1.571f);
Note: In C#,method
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in theMethodName
class to avoid allocating a newStringName on each call.
Variantcall_deferred(method:StringName, ...)vararg🔗
Calls themethod
on the object during idle time. Always returnsnull
,not the method's result.
Idle time happens mainly at the end of process and physics frames. In it, deferred calls will be run until there are none left, which means you can defer calls from other deferred calls and they'll still be run in the current idle time cycle. This means you should not call a method deferred from itself (or from a method called by it), as this causes infinite recursion the same way as if you had called the method directly.
This method supports a variable number of arguments, so parameters can be passed as a comma separated list.
varnode=Node3D.new()node.call_deferred("rotate",Vector3(1.0,0.0,0.0),1.571)
varnode=newNode3D();node.CallDeferred(Node3D.MethodName.Rotate,newVector3(1f,0f,0f),1.571f);
See alsoCallable.call_deferred().
Note: In C#,method
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in theMethodName
class to avoid allocating a newStringName on each call.
Note: If you're looking to delay the function call by a frame, refer to theSceneTree.process_frame andSceneTree.physics_frame signals.
varnode=Node3D.new()# Make a Callable and bind the arguments to the node's rotate() call.varcallable=node.rotate.bind(Vector3(1.0,0.0,0.0),1.571)# Connect the callable to the process_frame signal, so it gets called in the next process frame.# CONNECT_ONE_SHOT makes sure it only gets called once instead of every frame.get_tree().process_frame.connect(callable,CONNECT_ONE_SHOT)
Variantcallv(method:StringName, arg_array:Array)🔗
Calls themethod
on the object and returns the result. Unlikecall(), this method expects all parameters to be contained insidearg_array
.
varnode=Node3D.new()node.callv("rotate",[Vector3(1.0,0.0,0.0),1.571])
varnode=newNode3D();node.Callv(Node3D.MethodName.Rotate,[newVector3(1f,0f,0f),1.571f]);
Note: In C#,method
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in theMethodName
class to avoid allocating a newStringName on each call.
boolcan_translate_messages()const🔗
Returnstrue
if the object is allowed to translate messages withtr() andtr_n(). See alsoset_message_translation().
If this method is called duringNOTIFICATION_PREDELETE, this object will reject being freed and will remain allocated. This is mostly an internal function used for error handling to avoid the user from freeing objects when they are not intended to.
Errorconnect(signal:StringName, callable:Callable, flags:int = 0)🔗
Connects asignal
by name to acallable
. Optionalflags
can be also added to configure the connection's behavior (seeConnectFlags constants).
A signal can only be connected once to the sameCallable. If the signal is already connected, this method returns@GlobalScope.ERR_INVALID_PARAMETER and pushes an error message, unless the signal is connected withCONNECT_REFERENCE_COUNTED. To prevent this, useis_connected() first to check for existing connections.
If thecallable
's object is freed, 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.
func_ready():varbutton=Button.new()# `button_down` here is a Signal variant type, 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.varplayer=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])
publicoverridevoid_Ready(){varbutton=newButton();// 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.varplayer=newPlayer();// We can use lambdas when we need to bind additional parameters.player.Hit+=()=>OnPlayerHit("sword",100);}privatevoidOnButtonDown(){GD.Print("Button down!");}privatevoidOnPlayerHit(stringweaponType,intdamage){GD.Print($"Hit with weapon {weaponType} for {damage} damage.");}
``Object.connect()`` or ``Signal.connect()``?
As seen above, the recommended method to connect signals is notconnect(). The code block below shows the four options for connecting signals, using either this legacy method or the recommendedSignal.connect(), and using either an implicitCallable or a manually defined one.
func_ready():varbutton=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!")
publicoverridevoid_Ready(){varbutton=newButton();// Option 1: In C#, we can use signals as events and connect with this idiomatic syntax:button.ButtonDown+=OnButtonDown;// Option 2: GodotObject.Connect() with a constructed Callable from a method group.button.Connect(Button.SignalName.ButtonDown,Callable.From(OnButtonDown));// Option 3: GodotObject.Connect() with a constructed Callable using a target object and method name.button.Connect(Button.SignalName.ButtonDown,newCallable(this,MethodName.OnButtonDown));}privatevoidOnButtonDown(){GD.Print("Button down!");}
While all options have the same outcome (button
'sBaseButton.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 thebutton_down
Signal or the_on_button_down
Callable are not defined. 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 objectself
. 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.
Binding and passing parameters:
The syntax to bind parameters is throughCallable.bind(), which returns a copy of theCallable with its parameters bound.
When callingemit_signal() orSignal.emit(), the signal parameters can be also passed. The examples below show the relationship between these signal parameters and bound parameters.
func_ready():# This assumes that a `Player` class exists, which defines a `hit` signal.varplayer=Player.new()# Using Callable.bind().player.hit.connect(_on_player_hit.bind("sword",100))# Parameters added when emitting the signal are passed first.player.hit.emit("Dark lord",5)# We pass two arguments when emitting (`hit_by`, `level`),# and bind two more arguments 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])
publicoverridevoid_Ready(){// This assumes that a `Player` class exists, which defines a `Hit` signal.varplayer=newPlayer();// Using lambda expressions that create a closure that captures the additional parameters.// The lambda only receives the parameters defined by the signal's delegate.player.Hit+=(hitBy,level)=>OnPlayerHit(hitBy,level,"sword",100);// Parameters added when emitting the signal are passed first.player.EmitSignal(SignalName.Hit,"Dark lord",5);}// We pass two arguments when emitting (`hit_by`, `level`),// and bind two more arguments when connecting (`weapon_type`, `damage`).privatevoidOnPlayerHit(stringhitBy,intlevel,stringweaponType,intdamage){GD.Print($"Hit by {hitBy} (level {level}) with weapon {weaponType} for {damage} damage.");}
voiddisconnect(signal:StringName, callable:Callable)🔗
Disconnects asignal
by name from a givencallable
. If the connection does not exist, generates an error. Useis_connected() to make sure that the connection exists.
Erroremit_signal(signal:StringName, ...)vararg🔗
Emits the givensignal
by name. The signal must exist, so it should be a built-in signal of this class or one of its inherited classes, or a user-defined signal (seeadd_user_signal()). This method supports a variable number of arguments, so parameters can be passed as a comma separated list.
Returns@GlobalScope.ERR_UNAVAILABLE ifsignal
does not exist or the parameters are invalid.
emit_signal("hit","sword",100)emit_signal("game_over")
EmitSignal(SignalName.Hit,"sword",100);EmitSignal(SignalName.GameOver);
Note: In C#,signal
must be in snake_case when referring to built-in Godot signals. Prefer using the names exposed in theSignalName
class to avoid allocating a newStringName on each call.
Deletes the object from memory. Pre-existing references to the object become invalid, and any attempt to access them will result in a run-time error. Checking the references with@GlobalScope.is_instance_valid() will returnfalse
.
Variantget(property:StringName)const🔗
Returns theVariant value of the givenproperty
. If theproperty
does not exist, this method returnsnull
.
varnode=Node2D.new()node.rotation=1.5vara=node.get("rotation")# a is 1.5
varnode=newNode2D();node.Rotation=1.5f;vara=node.Get(Node2D.PropertyName.Rotation);// a is 1.5
Note: In C#,property
must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in thePropertyName
class to avoid allocating a newStringName on each call.
Returns the object's built-in class name, as aString. See alsois_class().
Note: This method ignoresclass_name
declarations. If this object's script has defined aclass_name
, the base, built-in class name is returned instead.
Array[Dictionary]get_incoming_connections()const🔗
Returns anArray of signal connections received by this object. Each connection is represented as aDictionary that contains three entries:
signal
is a reference to theSignal;callable
is a reference to theCallable;flags
is a combination ofConnectFlags.
Variantget_indexed(property_path:NodePath)const🔗
Gets the object's property indexed by the givenproperty_path
. The path should be aNodePath relative to the current object and can use the colon character (:
) to access nested properties.
Examples:"position:x"
or"material:next_pass:blend_mode"
.
varnode=Node2D.new()node.position=Vector2(5,-10)vara=node.get_indexed("position")# a is Vector2(5, -10)varb=node.get_indexed("position:y")# b is -10
varnode=newNode2D();node.Position=newVector2(5,-10);vara=node.GetIndexed("position");// a is Vector2(5, -10)varb=node.GetIndexed("position:y");// b is -10
Note: In C#,property_path
must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in thePropertyName
class to avoid allocating a newStringName on each call.
Note: This method does not support actual paths to nodes in theSceneTree, only sub-property paths. In the context of nodes, useNode.get_node_and_resource() instead.
Returns the object's unique instance ID. This ID can be saved inEncodedObjectAsID, and can be used to retrieve this object instance with@GlobalScope.instance_from_id().
Note: This ID is only useful during the current session. It won't correspond to a similar object if the ID is sent over a network, or loaded from a file at a later time.
Variantget_meta(name:StringName, default:Variant = null)const🔗
Returns the object's metadata value for the given entryname
. If the entry does not exist, returnsdefault
. Ifdefault
isnull
, an error is also generated.
Note: A metadata's name must be a valid identifier as perStringName.is_valid_identifier() method.
Note: Metadata that has a name starting with an underscore (_
) is considered editor-only. Editor-only metadata is not displayed in the Inspector and should not be edited, although it can still be found by this method.
Array[StringName]get_meta_list()const🔗
Returns the object's metadata entry names as anArray ofStringNames.
intget_method_argument_count(method:StringName)const🔗
Returns the number of arguments of the givenmethod
by name.
Note: In C#,method
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in theMethodName
class to avoid allocating a newStringName on each call.
Array[Dictionary]get_method_list()const🔗
Returns this object's methods and their signatures as anArray of dictionaries. EachDictionary contains the following entries:
name
is the name of the method, as aString;args
is anArray of dictionaries representing the arguments;default_args
is the default arguments as anArray of variants;flags
is a combination ofMethodFlags;id
is the method's internal identifierint;return
is the returned value, as aDictionary;
Note: The dictionaries ofargs
andreturn
are formatted identically to the results ofget_property_list(), although not all entries are used.
Array[Dictionary]get_property_list()const🔗
Returns the object's property list as anArray of dictionaries. EachDictionary contains the following entries:
name
is the property's name, as aString;class_name
is an emptyStringName, unless the property is@GlobalScope.TYPE_OBJECT and it inherits from a class;type
is the property's type, as anint (seeVariant.Type);hint
ishow the property is meant to be edited (seePropertyHint);hint_string
depends on the hint (seePropertyHint);usage
is a combination ofPropertyUsageFlags.
Note: In GDScript, all class members are treated as properties. In C# and GDExtension, it may be necessary to explicitly mark class members as Godot properties using decorators or attributes.
Returns the object'sScript instance, ornull
if no script is attached.
Array[Dictionary]get_signal_connection_list(signal:StringName)const🔗
Returns anArray of connections for the givensignal
name. Each connection is represented as aDictionary that contains three entries:
signal
is a reference to theSignal;callable
is a reference to the connectedCallable;flags
is a combination ofConnectFlags.
Array[Dictionary]get_signal_list()const🔗
Returns the list of existing signals as anArray of dictionaries.
Note: Due of the implementation, eachDictionary is formatted very similarly to the returned values ofget_method_list().
StringNameget_translation_domain()const🔗
Returns the name of the translation domain used bytr() andtr_n(). See alsoTranslationServer.
boolhas_connections(signal:StringName)const🔗
Returnstrue
if any connection exists on the givensignal
name.
Note: In C#,signal
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in theSignalName
class to avoid allocating a newStringName on each call.
boolhas_meta(name:StringName)const🔗
Returnstrue
if a metadata entry is found with the givenname
. See alsoget_meta(),set_meta() andremove_meta().
Note: A metadata's name must be a valid identifier as perStringName.is_valid_identifier() method.
Note: Metadata that has a name starting with an underscore (_
) is considered editor-only. Editor-only metadata is not displayed in the Inspector and should not be edited, although it can still be found by this method.
boolhas_method(method:StringName)const🔗
Returnstrue
if the givenmethod
name exists in the object.
Note: In C#,method
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in theMethodName
class to avoid allocating a newStringName on each call.
boolhas_signal(signal:StringName)const🔗
Returnstrue
if the givensignal
name exists in the object.
Note: In C#,signal
must be in snake_case when referring to built-in Godot signals. Prefer using the names exposed in theSignalName
class to avoid allocating a newStringName on each call.
boolhas_user_signal(signal:StringName)const🔗
Returnstrue
if the given user-definedsignal
name exists. Only signals added withadd_user_signal() are included. See alsoremove_user_signal().
boolis_blocking_signals()const🔗
Returnstrue
if the object is blocking its signals from being emitted. Seeset_block_signals().
boolis_class(class:String)const🔗
Returnstrue
if the object inherits from the givenclass
. See alsoget_class().
varsprite2d=Sprite2D.new()sprite2d.is_class("Sprite2D")# Returns truesprite2d.is_class("Node")# Returns truesprite2d.is_class("Node3D")# Returns false
varsprite2D=newSprite2D();sprite2D.IsClass("Sprite2D");// Returns truesprite2D.IsClass("Node");// Returns truesprite2D.IsClass("Node3D");// Returns false
Note: This method ignoresclass_name
declarations in the object's script.
boolis_connected(signal:StringName, callable:Callable)const🔗
Returnstrue
if a connection exists between the givensignal
name andcallable
.
Note: In C#,signal
must be in snake_case when referring to built-in Godot signals. Prefer using the names exposed in theSignalName
class to avoid allocating a newStringName on each call.
boolis_queued_for_deletion()const🔗
Returnstrue
if theNode.queue_free() method was called for the object.
voidnotification(what:int, reversed:bool = false)🔗
Sends the givenwhat
notification to all classes inherited by the object, triggering calls to_notification(), starting from the highest ancestor (theObject class) and going down to the object's script.
Ifreversed
istrue
, the call order is reversed.
varplayer=Node2D.new()player.set_script(load("res://player.gd"))player.notification(NOTIFICATION_ENTER_TREE)# The call order is Object -> Node -> Node2D -> player.gd.player.notification(NOTIFICATION_ENTER_TREE,true)# The call order is player.gd -> Node2D -> Node -> Object.
varplayer=newNode2D();player.SetScript(GD.Load("res://player.gd"));player.Notification(NotificationEnterTree);// The call order is GodotObject -> Node -> Node2D -> player.gd.player.Notification(NotificationEnterTree,true);// The call order is player.gd -> Node2D -> Node -> GodotObject.
voidnotify_property_list_changed()🔗
Emits theproperty_list_changed signal. This is mainly used to refresh the editor, so that the Inspector and editor plugins are properly updated.
boolproperty_can_revert(property:StringName)const🔗
Returnstrue
if the givenproperty
has a custom default value. Useproperty_get_revert() to get theproperty
's default value.
Note: This method is used by the Inspector dock to display a revert icon. The object must implement_property_can_revert() to customize the default value. If_property_can_revert() is not implemented, this method returnsfalse
.
Variantproperty_get_revert(property:StringName)const🔗
Returns the custom default value of the givenproperty
. Useproperty_can_revert() to check if theproperty
has a custom default value.
Note: This method is used by the Inspector dock to display a revert icon. The object must implement_property_get_revert() to customize the default value. If_property_get_revert() is not implemented, this method returnsnull
.
voidremove_meta(name:StringName)🔗
Removes the given entryname
from the object's metadata. See alsohas_meta(),get_meta() andset_meta().
Note: A metadata's name must be a valid identifier as perStringName.is_valid_identifier() method.
Note: Metadata that has a name starting with an underscore (_
) is considered editor-only. Editor-only metadata is not displayed in the Inspector and should not be edited, although it can still be found by this method.
voidremove_user_signal(signal:StringName)🔗
Removes the given user signalsignal
from the object. See alsoadd_user_signal() andhas_user_signal().
voidset(property:StringName, value:Variant)🔗
Assignsvalue
to the givenproperty
. If the property does not exist or the givenvalue
's type doesn't match, nothing happens.
varnode=Node2D.new()node.set("global_scale",Vector2(8,2.5))print(node.global_scale)# Prints (8.0, 2.5)
varnode=newNode2D();node.Set(Node2D.PropertyName.GlobalScale,newVector2(8,2.5f));GD.Print(node.GlobalScale);// Prints (8, 2.5)
Note: In C#,property
must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in thePropertyName
class to avoid allocating a newStringName on each call.
voidset_block_signals(enable:bool)🔗
If set totrue
, the object becomes unable to emit signals. As such,emit_signal() and signal connections will not work, until it is set tofalse
.
voidset_deferred(property:StringName, value:Variant)🔗
Assignsvalue
to the givenproperty
, at the end of the current frame. This is equivalent to callingset() throughcall_deferred().
varnode=Node2D.new()add_child(node)node.rotation=1.5node.set_deferred("rotation",3.0)print(node.rotation)# Prints 1.5awaitget_tree().process_frameprint(node.rotation)# Prints 3.0
varnode=newNode2D();node.Rotation=1.5f;node.SetDeferred(Node2D.PropertyName.Rotation,3f);GD.Print(node.Rotation);// Prints 1.5awaitToSignal(GetTree(),SceneTree.SignalName.ProcessFrame);GD.Print(node.Rotation);// Prints 3.0
Note: In C#,property
must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in thePropertyName
class to avoid allocating a newStringName on each call.
voidset_indexed(property_path:NodePath, value:Variant)🔗
Assigns a newvalue
to the property identified by theproperty_path
. The path should be aNodePath relative to this object, and can use the colon character (:
) to access nested properties.
varnode=Node2D.new()node.set_indexed("position",Vector2(42,0))node.set_indexed("position:y",-10)print(node.position)# Prints (42.0, -10.0)
varnode=newNode2D();node.SetIndexed("position",newVector2(42,0));node.SetIndexed("position:y",-10);GD.Print(node.Position);// Prints (42, -10)
Note: In C#,property_path
must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in thePropertyName
class to avoid allocating a newStringName on each call.
voidset_message_translation(enable:bool)🔗
If set totrue
, allows the object to translate messages withtr() andtr_n(). Enabled by default. See alsocan_translate_messages().
voidset_meta(name:StringName, value:Variant)🔗
Adds or changes the entryname
inside the object's metadata. The metadatavalue
can be anyVariant, although some types cannot be serialized correctly.
Ifvalue
isnull
, the entry is removed. This is the equivalent of usingremove_meta(). See alsohas_meta() andget_meta().
Note: A metadata's name must be a valid identifier as perStringName.is_valid_identifier() method.
Note: Metadata that has a name starting with an underscore (_
) is considered editor-only. Editor-only metadata is not displayed in the Inspector and should not be edited, although it can still be found by this method.
voidset_script(script:Variant)🔗
Attachesscript
to the object, and instantiates it. As a result, the script's_init() is called. AScript is used to extend the object's functionality.
If a script already exists, its instance is detached, and its property values and state are lost. Built-in property values are still kept.
voidset_translation_domain(domain:StringName)🔗
Sets the name of the translation domain used bytr() andtr_n(). See alsoTranslationServer.
Returns aString representing the object. Defaults to"<ClassName#RID>"
. Override_to_string() to customize the string representation of the object.
Stringtr(message:StringName, context:StringName = &"")const🔗
Translates amessage
, using the translation catalogs configured in the Project Settings. Furthercontext
can be specified to help with the translation. Note that mostControl nodes automatically translate their strings, so this method is mostly useful for formatted strings or custom drawn text.
Ifcan_translate_messages() isfalse
, or no translation is available, this method returns themessage
without changes. Seeset_message_translation().
For detailed examples, seeInternationalizing games.
Note: This method can't be used without anObject instance, as it requires thecan_translate_messages() method. To translate strings in a static context, useTranslationServer.translate().
Stringtr_n(message:StringName, plural_message:StringName, n:int, context:StringName = &"")const🔗
Translates amessage
orplural_message
, using the translation catalogs configured in the Project Settings. Furthercontext
can be specified to help with the translation.
Ifcan_translate_messages() isfalse
, or no translation is available, this method returnsmessage
orplural_message
, without changes. Seeset_message_translation().
Then
is the number, or amount, of the message's subject. It is used by the translation system to fetch the correct plural form for the current language.
For detailed examples, seeLocalization using gettext.
Note: Negative andfloat numbers may not properly apply to some countable subjects. It's recommended to handle these cases withtr().
Note: This method can't be used without anObject instance, as it requires thecan_translate_messages() method. To translate strings in a static context, useTranslationServer.translate_plural().