Class GodotObject
- Namespace
- Godot
- Assembly
- GodotSharp.dll
An advanced Variant 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, a Sprite2D instance is able to call AddChild(Node, bool, InternalMode) because it inherits from Node.
You can create new instances, using Object.new()
in GDScript, or new GodotObject
in C#.
To delete an Object instance, call Free(). 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 extension Resource) deletes itself when no longer referenced, and Node deletes its children when freed.
Objects can have a Script attached to them. Once the Script is instantiated, it effectively acts as an extension to the base class, allowing it to define and inherit new properties, methods and signals.
Inside a Script, _GetPropertyList() 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 [annotation @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 as Set(StringName, Variant), Get(StringName), Call(StringName, params Variant[]), HasMethod(StringName), HasSignal(StringName), etc. Note that these methods are much slower than direct references.
In GDScript, you can also check if a given property, method, or signal name exists in an object with the in
operator:
var node = Node.new()
print("name" in node) # Prints true
print("get_parent" in node) # Prints true
print("tree_entered" in node) # Prints true
print("unknown" in node) # Prints false
Notifications are int constants commonly sent and received by objects. For example, on every rendered frame, the SceneTree notifies nodes inside the tree with a NotificationProcess. The nodes receive it and may call _Process(double) to update. To make use of notifications, see Notification(int, bool) and _Notification(int).
Lastly, every object can also contain metadata (data about data). SetMeta(StringName, Variant) 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 a RefCounted, references to an object stored in a variable can become invalid without being set to null
. To check if an object has been deleted, do not compare it against null
. Instead, use @GlobalScope.is_instance_valid
. It's also recommended to inherit from RefCounted for classes storing data instead of GodotObject.
Note: The script
is not exposed like most properties. To set or get an object's Script in code, use SetScript(Variant) and GetScript(), respectively.
[GodotClassName("Object")]
public class GodotObject : IDisposable
- Inheritance
-
GodotObject
- Implements
- Derived
- Inherited Members
Constructors
GodotObject()
Constructs a new GodotObject.
public GodotObject()
Fields
NotificationExtensionReloaded
Notification received when the object finishes hot reloading. This notification is only sent for extensions classes and derived.
public const long NotificationExtensionReloaded = 2
Field Value
NotificationPostinitialize
Notification received when the object is initialized, before its script is attached. Used internally.
public const long NotificationPostinitialize = 0
Field Value
NotificationPredelete
Notification received when the object is about to be deleted. Can act as the deconstructor of some programming languages.
public const long NotificationPredelete = 1
Field Value
Properties
NativeInstance
The pointer to the native instance of this GodotObject.
public IntPtr NativeInstance { get; }
Property Value
Methods
AddUserSignal(string, Array)
Adds a user-defined signal
. Optional arguments for the signal can be added as an Array of dictionaries, each defining a name
string and a type
int (see Variant.Type). See also HasUserSignal(StringName).
AddUserSignal("Hurt", new Godot.Collections.Array()
{
new Godot.Collections.Dictionary()
{
{ "name", "damage" },
{ "type", (int)Variant.Type.Int }
},
new Godot.Collections.Dictionary()
{
{ "name", "source" },
{ "type", (int)Variant.Type.Object }
}
});
public void AddUserSignal(string signal, Array arguments = null)
Parameters
Call(StringName, params Variant[])
Calls the method
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.
var node = new Node3D();
node.Call(Node3D.MethodName.Rotate, new Vector3(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 the MethodName
class to avoid allocating a new StringName on each call.
public Variant Call(StringName method, params Variant[] args)
Parameters
method
StringNameargs
Variant[]
Returns
CallDeferred(StringName, params Variant[])
Calls the method
on the object during idle time. Always returns null, 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.
var node = new Node3D();
node.CallDeferred(Node3D.MethodName.Rotate, new Vector3(1f, 0f, 0f), 1.571f);
See also Callable.call_deferred
.
Note: In C#, method
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in the MethodName
class to avoid allocating a new StringName on each call.
Note: If you're looking to delay the function call by a frame, refer to the ProcessFrame and PhysicsFrame signals.
var node = Node3D.new()
# Make a Callable and bind the arguments to the node's rotate() call.
var callable = 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)
public Variant CallDeferred(StringName method, params Variant[] args)
Parameters
method
StringNameargs
Variant[]
Returns
Callv(StringName, Array)
Calls the method
on the object and returns the result. Unlike Call(StringName, params Variant[]), this method expects all parameters to be contained inside argArray
.
var node = new Node3D();
node.Callv(Node3D.MethodName.Rotate, new Godot.Collections.Array { new Vector3(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 the MethodName
class to avoid allocating a new StringName on each call.
public Variant Callv(StringName method, Array argArray)
Parameters
method
StringNameargArray
Array
Returns
CanTranslateMessages()
Returns true
if the object is allowed to translate messages with Tr(StringName, StringName) and TrN(StringName, StringName, int, StringName). See also SetMessageTranslation(bool).
public bool CanTranslateMessages()
Returns
CancelFree()
If this method is called during NotificationPredelete, 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.
public void CancelFree()
Connect(StringName, Callable, uint)
Connects a signal
by name to a callable
. Optional flags
can be also added to configure the connection's behavior (see GodotObject.ConnectFlags constants).
A signal can only be connected once to the same Callable. If the signal is already connected, this method returns InvalidParameter and pushes an error message, unless the signal is connected with ReferenceCounted. To prevent this, use IsConnected(StringName, Callable) first to check for existing connections.
If the callable
'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.
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();
// We can use lambdas when we need to bind additional parameters.
player.Hit += () => OnPlayerHit("sword", 100);
}
private void OnButtonDown()
{
GD.Print("Button down!");
}
private void OnPlayerHit(string weaponType, int damage)
{
GD.Print($"Hit with weapon {weaponType} for {damage} damage.");
}
Object.connect()
or Signal.connect()
?
As seen above, the recommended method to connect signals is not Connect(StringName, Callable, uint). 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.
public override void _Ready()
{
var button = new Button();
// 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, new Callable(this, MethodName.OnButtonDown));
}
private void OnButtonDown()
{
GD.Print("Button down!");
}
While all options have the same outcome (button
's ButtonDown 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 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 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.
Binding and passing parameters:
The syntax to bind parameters is through Callable.bind
, which returns a copy of the Callable with its parameters bound.
When calling EmitSignal(StringName, params Variant[]), the signal parameters can be also passed. The examples below show the relationship between these signal parameters and bound parameters.
public override void _Ready()
{
// This assumes that a `Player` class exists, which defines a `Hit` signal.
var player = new Player();
// 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
).
private void OnPlayerHit(string hitBy, int level, string weaponType, int damage)
{
GD.Print($"Hit by {hitBy} (level {level}) with weapon {weaponType} for {damage} damage.");
}
public Error Connect(StringName signal, Callable callable, uint flags = 0)
Parameters
signal
StringNamecallable
Callableflags
uint
Returns
Disconnect(StringName, Callable)
Disconnects a signal
by name from a given callable
. If the connection does not exist, generates an error. Use IsConnected(StringName, Callable) to make sure that the connection exists.
public void Disconnect(StringName signal, Callable callable)
Parameters
signal
StringNamecallable
Callable
Dispose()
Disposes of this GodotObject.
public void Dispose()
Dispose(bool)
Disposes implementation of this GodotObject.
protected virtual void Dispose(bool disposing)
Parameters
disposing
bool
EmitSignal(StringName, params Variant[])
Emits the given signal
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 (see AddUserSignal(string, Array)). This method supports a variable number of arguments, so parameters can be passed as a comma separated list.
Returns Unavailable if signal
does not exist or the parameters are invalid.
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 the SignalName
class to avoid allocating a new StringName on each call.
public Error EmitSignal(StringName signal, params Variant[] args)
Parameters
signal
StringNameargs
Variant[]
Returns
~GodotObject()
protected ~GodotObject()
Free()
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 return false
.
public void Free()
Get(StringName)
Returns the Variant value of the given property
. If the property
does not exist, this method returns null
.
var node = new Node2D();
node.Rotation = 1.5f;
var a = 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 the PropertyName
class to avoid allocating a new StringName on each call.
public Variant Get(StringName property)
Parameters
property
StringName
Returns
GetClass()
Returns the object's built-in class name, as a string. See also IsClass(string).
Note: This method ignores class_name
declarations. If this object's script has defined a class_name
, the base, built-in class name is returned instead.
public string GetClass()
Returns
GetIncomingConnections()
Returns an Array of signal connections received by this object. Each connection is represented as a Dictionary that contains three entries:
- signal
is a reference to the Signal;
- callable
is a reference to the Callable;
- flags
is a combination of GodotObject.ConnectFlags.
public Array<Dictionary> GetIncomingConnections()
Returns
GetIndexed(NodePath)
Gets the object's property indexed by the given propertyPath
. The path should be a NodePath relative to the current object and can use the colon character (:
) to access nested properties.
Examples:
"position:x"
or "material:next_pass:blend_mode"
.
var node = new Node2D();
node.Position = new Vector2(5, -10);
var a = node.GetIndexed("position"); // a is Vector2(5, -10)
var b = node.GetIndexed("position:y"); // b is -10
Note: In C#, propertyPath
must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in the PropertyName
class to avoid allocating a new StringName on each call.
Note: This method does not support actual paths to nodes in the SceneTree, only sub-property paths. In the context of nodes, use GetNodeAndResource(NodePath) instead.
public Variant GetIndexed(NodePath propertyPath)
Parameters
propertyPath
NodePath
Returns
GetInstanceId()
Returns the object's unique instance ID. This ID can be saved in EncodedObjectAsId, and can be used to retrieve this object instance with @GlobalScope.instance_from_id
.
public ulong GetInstanceId()
Returns
GetMeta(StringName, Variant)
Returns the object's metadata value for the given entry name
. If the entry does not exist, returns default
. If default
is null
, an error is also generated.
Note: A metadata's name must be a valid identifier as per StringName.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.
public Variant GetMeta(StringName name, Variant @default = default)
Parameters
name
StringNamedefault
Variant
Returns
GetMetaList()
Returns the object's metadata entry names as a string[].
public Array<StringName> GetMetaList()
Returns
GetMethodList()
Returns this object's methods and their signatures as an Array of dictionaries. Each Dictionary contains the following entries:
- name
is the name of the method, as a string;
- args
is an Array of dictionaries representing the arguments;
- default_args
is the default arguments as an Array of variants;
- flags
is a combination of MethodFlags;
- id
is the method's internal identifier int;
- return
is the returned value, as a Dictionary;
Note: The dictionaries of args
and return
are formatted identically to the results of GetPropertyList(), although not all entries are used.
public Array<Dictionary> GetMethodList()
Returns
GetPropertyList()
Returns the object's property list as an Array of dictionaries. Each Dictionary contains the following entries:
- name
is the property's name, as a string;
- class_name
is an empty StringName, unless the property is Object and it inherits from a class;
- type
is the property's type, as an int (see Variant.Type);
- hint
is how the property is meant to be edited (see PropertyHint);
- hint_string
depends on the hint (see PropertyHint);
- usage
is a combination of PropertyUsageFlags.
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.
public Array<Dictionary> GetPropertyList()
Returns
GetScript()
Returns the object's Script instance, or null
if no script is attached.
public Variant GetScript()
Returns
GetSignalConnectionList(StringName)
Returns an Array of connections for the given signal
name. Each connection is represented as a Dictionary that contains three entries:
- signal
is a reference to the Signal;
- callable
is a reference to the connected Callable;
- flags
is a combination of GodotObject.ConnectFlags.
public Array<Dictionary> GetSignalConnectionList(StringName signal)
Parameters
signal
StringName
Returns
GetSignalList()
Returns the list of existing signals as an Array of dictionaries.
Note: Due of the implementation, each Dictionary is formatted very similarly to the returned values of GetMethodList().
public Array<Dictionary> GetSignalList()
Returns
HasGodotClassMethod(in godot_string_name)
Check if the type contains a method with the given name. This method is used by Godot to check if a method exists before invoking it. Do not call or override this method.
protected virtual bool HasGodotClassMethod(in godot_string_name method)
Parameters
method
godot_string_nameName of the method to check for.
Returns
HasGodotClassSignal(in godot_string_name)
Check if the type contains a signal with the given name. This method is used by Godot to check if a signal exists before raising it. Do not call or override this method.
protected virtual bool HasGodotClassSignal(in godot_string_name signal)
Parameters
signal
godot_string_nameName of the signal to check for.
Returns
HasMeta(StringName)
Returns true
if a metadata entry is found with the given name
. See also GetMeta(StringName, Variant), SetMeta(StringName, Variant) and RemoveMeta(StringName).
Note: A metadata's name must be a valid identifier as per StringName.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.
public bool HasMeta(StringName name)
Parameters
name
StringName
Returns
HasMethod(StringName)
Returns true
if the given method
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 the MethodName
class to avoid allocating a new StringName on each call.
public bool HasMethod(StringName method)
Parameters
method
StringName
Returns
HasSignal(StringName)
Returns true
if the given signal
name exists in the object.
Note: In C#, signal
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in the SignalName
class to avoid allocating a new StringName on each call.
public bool HasSignal(StringName signal)
Parameters
signal
StringName
Returns
HasUserSignal(StringName)
Returns true
if the given user-defined signal
name exists. Only signals added with AddUserSignal(string, Array) are included.
public bool HasUserSignal(StringName signal)
Parameters
signal
StringName
Returns
InstanceFromId(ulong)
Returns the GodotObject that corresponds to instanceId
.
All Objects have a unique instance ID. See also GetInstanceId().
public static GodotObject InstanceFromId(ulong instanceId)
Parameters
instanceId
ulongInstance ID of the Object to retrieve.
Returns
- GodotObject
The GodotObject instance.
Examples
public partial class MyNode : Node
{
public string Foo { get; set; } = "bar";
public override void _Ready()
{
ulong id = GetInstanceId();
var inst = (MyNode)InstanceFromId(Id);
GD.Print(inst.Foo); // Prints bar
}
}
InvokeGodotClassMethod(in godot_string_name, NativeVariantPtrArgs, out godot_variant)
Invokes the method with the given name, using the given arguments. This method is used by Godot to invoke methods from the engine side. Do not call or override this method.
protected virtual bool InvokeGodotClassMethod(in godot_string_name method, NativeVariantPtrArgs args, out godot_variant ret)
Parameters
method
godot_string_nameName of the method to invoke.
args
NativeVariantPtrArgsArguments to use with the invoked method.
ret
godot_variantValue returned by the invoked method.
Returns
IsBlockingSignals()
Returns true
if the object is blocking its signals from being emitted. See SetBlockSignals(bool).
public bool IsBlockingSignals()
Returns
IsClass(string)
Returns true
if the object inherits from the given class
. See also GetClass().
var sprite2D = new Sprite2D();
sprite2D.IsClass("Sprite2D"); // Returns true
sprite2D.IsClass("Node"); // Returns true
sprite2D.IsClass("Node3D"); // Returns false
Note: This method ignores class_name
declarations in the object's script.
public bool IsClass(string @class)
Parameters
class
string
Returns
IsConnected(StringName, Callable)
Returns true
if a connection exists between the given signal
name and callable
.
Note: In C#, signal
must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in the SignalName
class to avoid allocating a new StringName on each call.
public bool IsConnected(StringName signal, Callable callable)
Parameters
signal
StringNamecallable
Callable
Returns
IsInstanceIdValid(ulong)
Returns true if the GodotObject that corresponds
to id
is a valid object (e.g. has not been deleted from
memory). All Objects have a unique instance ID.
public static bool IsInstanceIdValid(ulong id)
Parameters
id
ulongThe Object ID to check.
Returns
- bool
If the instance with the given ID is a valid object.
IsInstanceValid(GodotObject)
Returns true if instance
is a
valid GodotObject (e.g. has not been deleted from memory).
public static bool IsInstanceValid(GodotObject instance)
Parameters
instance
GodotObjectThe instance to check.
Returns
- bool
If the instance is a valid object.
IsQueuedForDeletion()
Returns true
if the QueueFree() method was called for the object.
public bool IsQueuedForDeletion()
Returns
Notification(int, bool)
Sends the given what
notification to all classes inherited by the object, triggering calls to _Notification(int), starting from the highest ancestor (the GodotObject class) and going down to the object's script.
If reversed
is true
, the call order is reversed.
var player = new Node2D();
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.
public void Notification(int what, bool reversed = false)
Parameters
NotifyPropertyListChanged()
Emits the PropertyListChanged signal. This is mainly used to refresh the editor, so that the Inspector and editor plugins are properly updated.
public void NotifyPropertyListChanged()
PropertyCanRevert(StringName)
Returns true
if the given property
has a custom default value. Use PropertyGetRevert(StringName) to get the property
's default value.
Note: This method is used by the Inspector dock to display a revert icon. The object must implement _PropertyCanRevert(StringName) to customize the default value. If _PropertyCanRevert(StringName) is not implemented, this method returns false
.
public bool PropertyCanRevert(StringName property)
Parameters
property
StringName
Returns
PropertyGetRevert(StringName)
Returns the custom default value of the given property
. Use PropertyCanRevert(StringName) to check if the property
has a custom default value.
Note: This method is used by the Inspector dock to display a revert icon. The object must implement _PropertyGetRevert(StringName) to customize the default value. If _PropertyGetRevert(StringName) is not implemented, this method returns null
.
public Variant PropertyGetRevert(StringName property)
Parameters
property
StringName
Returns
RemoveMeta(StringName)
Removes the given entry name
from the object's metadata. See also HasMeta(StringName), GetMeta(StringName, Variant) and SetMeta(StringName, Variant).
Note: A metadata's name must be a valid identifier as per StringName.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.
public void RemoveMeta(StringName name)
Parameters
name
StringName
Set(StringName, Variant)
Assigns value
to the given property
. If the property does not exist or the given value
's type doesn't match, nothing happens.
var node = new Node2D();
node.Set(Node2D.PropertyName.GlobalScale, new Vector2(8, 2.5));
GD.Print(node.GlobalScale); // Prints Vector2(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 the PropertyName
class to avoid allocating a new StringName on each call.
public void Set(StringName property, Variant value)
Parameters
property
StringNamevalue
Variant
SetBlockSignals(bool)
If set to true
, the object becomes unable to emit signals. As such, EmitSignal(StringName, params Variant[]) and signal connections will not work, until it is set to false
.
public void SetBlockSignals(bool enable)
Parameters
enable
bool
SetDeferred(StringName, Variant)
Assigns value
to the given property
, at the end of the current frame. This is equivalent to calling Set(StringName, Variant) through CallDeferred(StringName, params Variant[]).
var node = new Node2D();
node.Rotation = 1.5f;
node.SetDeferred(Node2D.PropertyName.Rotation, 3f);
GD.Print(node.Rotation); // Prints 1.5
await ToSignal(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 the PropertyName
class to avoid allocating a new StringName on each call.
public void SetDeferred(StringName property, Variant value)
Parameters
property
StringNamevalue
Variant
SetIndexed(NodePath, Variant)
Assigns a new value
to the property identified by the propertyPath
. The path should be a NodePath relative to this object, and can use the colon character (:
) to access nested properties.
var node = new Node2D();
node.SetIndexed("position", new Vector2(42, 0));
node.SetIndexed("position:y", -10);
GD.Print(node.Position); // Prints (42, -10)
Note: In C#, propertyPath
must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in the PropertyName
class to avoid allocating a new StringName on each call.
public void SetIndexed(NodePath propertyPath, Variant value)
Parameters
SetMessageTranslation(bool)
If set to true
, allows the object to translate messages with Tr(StringName, StringName) and TrN(StringName, StringName, int, StringName). Enabled by default. See also CanTranslateMessages().
public void SetMessageTranslation(bool enable)
Parameters
enable
bool
SetMeta(StringName, Variant)
Adds or changes the entry name
inside the object's metadata. The metadata value
can be any Variant, although some types cannot be serialized correctly.
If value
is null
, the entry is removed. This is the equivalent of using RemoveMeta(StringName). See also HasMeta(StringName) and GetMeta(StringName, Variant).
Note: A metadata's name must be a valid identifier as per StringName.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.
public void SetMeta(StringName name, Variant value)
Parameters
name
StringNamevalue
Variant
SetScript(Variant)
Attaches script
to the object, and instantiates it. As a result, the script's GodotObject() is called. A Script 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.
public void SetScript(Variant script)
Parameters
script
Variant
ToSignal(GodotObject, StringName)
Returns a new SignalAwaiter awaiter configured to complete when the instance
source
emits the signal specified by the signal
parameter.
public SignalAwaiter ToSignal(GodotObject source, StringName signal)
Parameters
source
GodotObjectThe instance the awaiter will be listening to.
signal
StringNameThe signal the awaiter will be waiting for.
Returns
- SignalAwaiter
A SignalAwaiter that completes when
source
emits thesignal
.
Examples
This sample prints a message once every frame up to 100 times.
public override void _Ready()
{
for (int i = 0; i < 100; i++)
{
await ToSignal(GetTree(), "process_frame");
GD.Print($"Frame {i}");
}
}
ToString()
Converts this GodotObject to a string.
public override string ToString()
Returns
- string
A string representation of this object.
Tr(StringName, StringName)
Translates a message
, using the translation catalogs configured in the Project Settings. Further context
can be specified to help with the translation.
If CanTranslateMessages() is false
, or no translation is available, this method returns the message
without changes. See SetMessageTranslation(bool).
For detailed examples, see Internationalizing games.
public string Tr(StringName message, StringName context = null)
Parameters
message
StringNamecontext
StringName
Returns
TrN(StringName, StringName, int, StringName)
Translates a message
or pluralMessage
, using the translation catalogs configured in the Project Settings. Further context
can be specified to help with the translation.
If CanTranslateMessages() is false
, or no translation is available, this method returns message
or pluralMessage
, without changes. See SetMessageTranslation(bool).
The n
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, see Localization using gettext.
Note: Negative and float numbers may not properly apply to some countable subjects. It's recommended handling these cases with Tr(StringName, StringName).
public string TrN(StringName message, StringName pluralMessage, int n, StringName context = null)
Parameters
message
StringNamepluralMessage
StringNamen
intcontext
StringName
Returns
WeakRef(GodotObject)
Returns a weak reference to an object, or null if the argument is invalid. A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.
public static WeakRef WeakRef(GodotObject obj)
Parameters
obj
GodotObjectThe object.
Returns
- WeakRef
The WeakRef(GodotObject) reference to the object or null.
_Get(StringName)
Override this method to customize the behavior of Get(StringName). Should return the given property
's value, or null
if the property
should be handled normally.
Combined with _Set(StringName, Variant) and _GetPropertyList(), this method allows defining custom properties, which is particularly useful for editor plugins. Note that a property must be present in GetPropertyList(), otherwise this method will not be called.
public override Variant _Get(StringName property)
{
if (property == "FakeProperty")
{
GD.Print("Getting my property!");
return 4;
}
return default;
}
public override Godot.Collections.Array<Godot.Collections.Dictionary> _GetPropertyList()
{
return new Godot.Collections.Array<Godot.Collections.Dictionary>()
{
new Godot.Collections.Dictionary()
{
{ "name", "FakeProperty" },
{ "type", (int)Variant.Type.Int }
}
};
}
public virtual Variant _Get(StringName property)
Parameters
property
StringName
Returns
_GetPropertyList()
Override this method to customize how script properties should be handled by the engine.
Should return a property list, as an Array of dictionaries. The result is added to the array of GetPropertyList(), and should be formatted in the same way. Each Dictionary must at least contain the name
and type
entries.
The example below displays hammer_type
in the Inspector dock, only if holding_hammer
is true
:
[Tool]
public partial class MyNode2D : Node2D
{
private bool _holdingHammer;
[Export]
public bool HoldingHammer
{
get => _holdingHammer;
set
{
_holdingHammer = value;
NotifyPropertyListChanged();
}
}
public int HammerType { get; set; }
public override Godot.Collections.Array<Godot.Collections.Dictionary> _GetPropertyList()
{
// By default, `HammerType` is not visible in the editor.
var propertyUsage = PropertyUsageFlags.NoEditor;
if (HoldingHammer)
{
propertyUsage = PropertyUsageFlags.Default;
}
var properties = new Godot.Collections.Array<Godot.Collections.Dictionary>();
properties.Add(new Godot.Collections.Dictionary()
{
{ "name", "HammerType" },
{ "type", (int)Variant.Type.Int },
{ "usage", (int)propertyUsage }, // See above assignment.
{ "hint", (int)PropertyHint.Enum },
{ "hint_string", "Wooden,Iron,Golden,Enchanted" }
});
return properties;
}
}
Note: This method is intended for advanced purposes. For most common use cases, the scripting languages offer easier ways to handle properties. See [annotation @GDScript.@export], [annotation @GDScript.@export_enum], [annotation @GDScript.@export_group], etc.
Note: If the object's script is not [annotation @GDScript.@tool], this method will not be called in the editor.
public virtual Array<Dictionary> _GetPropertyList()
Returns
_Notification(int)
Called when the object receives a notification, which can be identified in what
by comparing it with a constant. See also Notification(int, bool).
public override void _Notification(int what)
{
if (what == NotificationPredelete)
{
GD.Print("Goodbye!");
}
}
Note: The base GodotObject defines a few notifications (NotificationPostinitialize and NotificationPredelete). Inheriting classes such as Node define a lot more notifications, which are also received by this method.
public virtual void _Notification(int what)
Parameters
what
int
_PropertyCanRevert(StringName)
Override this method to customize the given property
's revert behavior. Should return true
if the property
can be reverted in the Inspector dock. Use _PropertyGetRevert(StringName) to specify the property
's default value.
Note: This method must return consistently, regardless of the current value of the property
.
public virtual bool _PropertyCanRevert(StringName property)
Parameters
property
StringName
Returns
_PropertyGetRevert(StringName)
Override this method to customize the given property
's revert behavior. Should return the default value for the property
. If the default value differs from the property
's current value, a revert icon is displayed in the Inspector dock.
Note: _PropertyCanRevert(StringName) must also be overridden for this method to be called.
public virtual Variant _PropertyGetRevert(StringName property)
Parameters
property
StringName
Returns
_Set(StringName, Variant)
Override this method to customize the behavior of Set(StringName, Variant). Should set the property
to value
and return true
, or false
if the property
should be handled normally. The exact way to set the property
is up to this method's implementation.
Combined with _Get(StringName) and _GetPropertyList(), this method allows defining custom properties, which is particularly useful for editor plugins. Note that a property must be present in GetPropertyList(), otherwise this method will not be called.
private Godot.Collections.Dictionary _internalData = new Godot.Collections.Dictionary();
public override bool _Set(StringName property, Variant value)
{
if (property == "FakeProperty")
{
// Storing the value in the fake property.
_internalData["FakeProperty"] = value;
return true;
}
return false;
}
public override Godot.Collections.Array<Godot.Collections.Dictionary> _GetPropertyList()
{
return new Godot.Collections.Array<Godot.Collections.Dictionary>()
{
new Godot.Collections.Dictionary()
{
{ "name", "FakeProperty" },
{ "type", (int)Variant.Type.Int }
}
};
}
public virtual bool _Set(StringName property, Variant value)
Parameters
property
StringNamevalue
Variant
Returns
_ValidateProperty(Dictionary)
Override this method to customize existing properties. Every property info goes through this method. The dictionary contents is the same as in _GetPropertyList().
[Tool]
public partial class MyNode : Node
{
private bool _isNumberEditable;
[Export]
public bool IsNumberEditable
{
get => _isNumberEditable;
set
{
_isNumberEditable = value;
NotifyPropertyListChanged();
}
}
[Export]
public int Number { get; set; }
public override void _ValidateProperty(Godot.Collections.Dictionary property)
{
if (property["name"].AsStringName() == PropertyName.Number && IsNumberEditable)
{
var usage = property["usage"].As<PropertyUsageFlags>() | PropertyUsageFlags.ReadOnly;
property["usage"] = (int)usage;
}
}
}
public virtual void _ValidateProperty(Dictionary property)
Parameters
property
Dictionary
Events
PropertyListChanged
Emitted when NotifyPropertyListChanged() is called.
public event Action PropertyListChanged
Event Type
ScriptChanged
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 with Deferred.
public event Action ScriptChanged