Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Object
派生: 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
引擎中所有其他类的基类。
描述
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 Node.add_child 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, _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 as set, get, call, has_method, has_signal, 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 Node.NOTIFICATION_PROCESS. The nodes receive it and may call Node._process to update. To make use of notifications, see notification 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 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 Object.
Note: The script
is not exposed like most properties. To set or get an object's Script in code, use set_script and get_script, respectively.
Note: In a boolean context, an Object will evaluate to false
if it is equal to null
or it has been freed. Otherwise, an Object will always evaluate to true
. See also @GlobalScope.is_instance_valid.
教程
方法
信号
property_list_changed() 🔗
调用 notify_property_list_changed 时发出。
script_changed() 🔗
该对象的脚本发生改变时发出。
注意:发出这个信号时,新脚本还没有初始化。如果你需要访问新脚本,请用 CONNECT_DEFERRED 推迟与这个信号的连接。
枚举
enum ConnectFlags: 🔗
ConnectFlags CONNECT_DEFERRED = 1
延迟连接会在空闲时触发 Callable(当前帧的末尾),不会立即触发。
ConnectFlags CONNECT_PERSIST = 2
持久连接会在序列化对象时存储(比如使用 PackedScene.pack 时)。在编辑器中,通过“节点”面板创建的连接总是持久的。
ConnectFlags CONNECT_ONE_SHOT = 4
一次性连接,会在触发后自行断开。
ConnectFlags CONNECT_REFERENCE_COUNTED = 8
引用计数连接可以多次分配给同一个 Callable。每断开一次连接会让内部计数器减一。信号会在计数器变为 0 时完全断开连接。
常量
NOTIFICATION_POSTINITIALIZE = 0
🔗
该对象初始化时收到的通知,发生在附加脚本之前。内部使用。
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
🔗
当对象完成热重加载时收到的通知。该通知仅针对扩展类和派生类发送。
方法说明
Variant _get(property: StringName) virtual 🔗
Override this method to customize the behavior of get. Should return the given property
's value, or null
if the property
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 in get_property_list, otherwise this method will not be called.
func _get(property):
if property == "fake_property":
print("Getting my property!")
return 4
func _get_property_list():
return [
{ "name": "fake_property", "type": TYPE_INT }
]
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.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 an Array of dictionaries. The result is added to the array of get_property_list, and should be formatted in the same way. Each Dictionary must at least contain the name
and type
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 from ZERO
to FIVE
, with number_count
controlling the size of the list:
@tool
extends Node
@export var number_count = 3:
set(nc):
number_count = nc
numbers.resize(number_count)
notify_property_list_changed()
var numbers = PackedInt32Array([0, 0, 0])
func _get_property_list():
var properties = []
for i in range(number_count):
properties.append({
"name": "number_%d" % i,
"type": TYPE_INT,
"hint": PROPERTY_HINT_ENUM,
"hint_string": "ZERO,ONE,TWO,THREE,FOUR,FIVE",
})
return properties
func _get(property):
if property.begins_with("number_"):
var index = property.get_slice("_", 1).to_int()
return numbers[index]
func _set(property, value):
if property.begins_with("number_"):
var index = property.get_slice("_", 1).to_int()
numbers[index] = value
return true
return false
[Tool]
public partial class MyNode : Node
{
private int _numberCount;
[Export]
public int NumberCount
{
get => _numberCount;
set
{
_numberCount = value;
_numbers.Resize(_numberCount);
NotifyPropertyListChanged();
}
}
private Godot.Collections.Array<int> _numbers = [];
public override Godot.Collections.Array<Godot.Collections.Dictionary> _GetPropertyList()
{
Godot.Collections.Array<Godot.Collections.Dictionary> properties = [];
for (int i = 0; i < _numberCount; i++)
{
properties.Add(new Godot.Collections.Dictionary()
{
{ "name", $"number_{i}" },
{ "type", (int)Variant.Type.Int },
{ "hint", (int)PropertyHint.Enum },
{ "hint_string", "Zero,One,Two,Three,Four,Five" },
});
}
return properties;
}
public override Variant _Get(StringName property)
{
string propertyName = property.ToString();
if (propertyName.StartsWith("number_"))
{
int index = int.Parse(propertyName.Substring("number_".Length));
return _numbers[index];
}
return default;
}
public override bool _Set(StringName property, Variant value)
{
string propertyName = property.ToString();
if (propertyName.StartsWith("number_"))
{
int index = int.Parse(propertyName.Substring("number_".Length));
_numbers[index] = value.As<int>();
return true;
}
return false;
}
}
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.
void _init() virtual 🔗
实例化对象的脚本时调用,通常是在对象在内存中初始化之后(通过 GDScript 中的 Object.new()
或 C# 中的 new GodotObject
)。也可以将其定义为接受参数的形式。该方法类似于大多数编程语言中的构造函数。
注意:如果为 _init 定义了必填的参数,则带脚本的 Object 只能直接创建。使用任何其他方式(例如 PackedScene.instantiate 或 Node.duplicate)创建时,该脚本的初始化都将失败。
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 no Array 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. Returns true
so long as the iterator has not reached the end.
Example:
class MyRange:
var _from
var _to
func _init(from, to):
assert(from <= to)
_from = from
_to = to
func _iter_init(iter):
iter[0] = _from
return iter[0] < _to
func _iter_next(iter):
iter[0] += 1
return iter[0] < _to
func _iter_get(iter):
return iter
func _ready():
var my_range = MyRange.new(2, 5)
for x in my_range:
print(x) # Prints 2, 3, 4.
Note: Alternatively, you can ignore iter
and use the object's state instead, see online 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. Returns true
so long as the iterator has not reached the end.
void _notification(what: int) virtual 🔗
当对象收到通知时被调用,可以通过将 what
与常量比较来识别通知。另见 notification。
func _notification(what):
if what == NOTIFICATION_PREDELETE:
print("再见!")
public override void _Notification(int what)
{
if (what == NotificationPredelete)
{
GD.Print("再见!");
}
}
注意:基类 Object 定义了一些通知(NOTIFICATION_POSTINITIALIZE 和 NOTIFICATION_PREDELETE)。Node 等继承类定义了更多通知,这些通知也由该方法接收。
bool _property_can_revert(property: StringName) virtual 🔗
覆盖该方法以自定义给定 property
的恢复行为。如果 property
具有自定义默认值并且可在检查器面板中恢复,则应返回 true
。使用 _property_get_revert 来指定 property
的默认值。
注意:无论 property
的当前值如何,该方法都必须始终如一地返回。
Variant _property_get_revert(property: StringName) virtual 🔗
覆盖该方法以自定义给定 property
的还原行为。应返回 property
的默认值。如果默认值与 property
的当前值不同,则检查器停靠面板中会显示一个还原图标。
注意:_property_can_revert 也必须被覆盖,该方法才能被调用。
bool _set(property: StringName, value: Variant) virtual 🔗
Override this method to customize the behavior of set. 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 and _get_property_list, this method allows defining custom properties, which is particularly useful for editor plugins. Note that a property must be present in get_property_list, otherwise this method will not be called.
var internal_data = {}
func _set(property, value):
if property == "fake_property":
# Storing the value in the fake property.
internal_data["fake_property"] = value
return true
return false
func _get_property_list():
return [
{ "name": "fake_property", "type": TYPE_INT }
]
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.Dictionary()
{
{ "name", "FakeProperty" },
{ "type", (int)Variant.Type.Int },
},
];
}
Override this method to customize the return value of to_string, and therefore the object's representation as a String.
func _to_string():
return "Welcome to Godot 4!"
func _init():
print(self) # Prints "Welcome to Godot 4!"
var a = str(self) # a is "Welcome to Godot 4!"
void _validate_property(property: Dictionary) virtual 🔗
覆盖该方法以自定义已有属性。除了使用 _get_property_list 添加的属性之外,每个属性信息都经过该方法。字典内容与 _get_property_list 中的相同。
@tool
extends Node
@export var is_number_editable: bool:
set(value):
is_number_editable = value
notify_property_list_changed()
@export var number: int
func _validate_property(property: Dictionary):
if property.name == "number" and not is_number_editable:
property.usage |= PROPERTY_USAGE_READ_ONLY
[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;
}
}
}
void add_user_signal(signal: String, arguments: Array = []) 🔗
Adds a user-defined signal named 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 has_user_signal and remove_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 },
},
]);
Variant call(method: StringName, ...) vararg 🔗
在对象上调用 method
并返回结果。该方法支持可变数量的参数,因此参数可以作为逗号分隔的列表传递。
var node = Node3D.new()
node.call("rotate", Vector3(1.0, 0.0, 0.0), 1.571)
var node = new Node3D();
node.Call(Node3D.MethodName.Rotate, new Vector3(1f, 0f, 0f), 1.571f);
注意:在 C# 中,在引用 Godot 内置方法时,method
必须为 snake_case 格式。最好使用 MethodName
类中公开的名称,以避免在每次调用时分配新的 StringName。
Variant call_deferred(method: StringName, ...) vararg 🔗
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 = Node3D.new()
node.call_deferred("rotate", Vector3(1.0, 0.0, 0.0), 1.571)
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 SceneTree.process_frame and SceneTree.physics_frame 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)
Variant callv(method: StringName, arg_array: Array) 🔗
Calls the method
on the object and returns the result. Unlike call, this method expects all parameters to be contained inside arg_array
.
var node = Node3D.new()
node.callv("rotate", [Vector3(1.0, 0.0, 0.0), 1.571])
var node = new Node3D();
node.Callv(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.
bool can_translate_messages() const 🔗
如果允许该对象使用 tr 和 tr_n 翻译消息,则返回 true
。另见 set_message_translation。
void cancel_free() 🔗
如果在 NOTIFICATION_PREDELETE 时调用该方法,则该对象拒绝释放,仍会保持已分配的状态。主要是作为内部函数使用,用于错误处理,避免用户释放不想释放的对象。
Error connect(signal: StringName, callable: Callable, flags: int = 0) 🔗
按名称将 signal
连接到 callable
。还可以添加可选的 flags
来配置该连接的行为(请参阅 ConnectFlags 常量)。
一个信号只能连接到同一个 Callable 一次。如果该信号已经连接,除非该信号是使用 CONNECT_REFERENCE_COUNTED 连接的,否则该方法会返回 @GlobalScope.ERR_INVALID_PARAMETER 并推送一条错误消息。为防止这种情况,请首先使用 is_connected 检查已存在的连接。
如果 callable
的对象被释放,则该连接将会丢失。
推荐语法的示例:
连接信号是 Godot 中最常见的操作之一,API 提供了许多这样做的选项,这些选项将在下面进一步介绍。下面的代码块显示了推荐的方法。
func _ready():
var button = Button.new()
# 这里的 `button_down` 是一个 Signal 变体类型,因此我们调用 Signal.connect() 方法,而不是 Object.connect()。
# 请参阅下面的讨论以更深入地了解该 API。
button.button_down.connect(_on_button_down)
# 这假设存在一个“Player”类,它定义了一个“hit”信号。
var player = Player.new()
# 我们再次使用 Signal.connect() ,并且我们还使用了 Callable.bind() 方法,
# 它返回一个带有参数绑定的新 Callable。
player.hit.connect(_on_player_hit.bind("剑", 100))
func _on_button_down():
print("按钮按下!")
func _on_player_hit(weapon_type, damage):
print("用武器 %s 击中,造成 %d 伤害。" % [weapon_type, damage])
public override void _Ready()
{
var button = new Button();
// C# 支持将信号作为事件传递,因此我们可以使用这个惯用的构造:
button.ButtonDown += OnButtonDown;
// 这假设存在一个“Player”类,它定义了一个“Hit”信号。
var player = new Player();
// 当我们需要绑定额外的参数时,我们可以使用 Lambda 表达式。
player.Hit += () => OnPlayerHit("剑", 100);
}
private void OnButtonDown()
{
GD.Print("按钮按下!");
}
private void OnPlayerHit(string weaponType, int damage)
{
GD.Print($"用武器 {weaponType} 击中,造成 {damage} 伤害。");
}
``Object.connect()`` 还是 ``Signal.connect()``?
如上所示,推荐的连接信号的方法不是 connect。下面的代码块显示了连接信号的四个选项,使用该传统方法或推荐的 Signal.connect,并使用一个隐式的 Callable 或手动定义的 Callable。
func _ready():
var button = Button.new()
# 选项 1:Object.connect() 并使用已定义的函数的隐式 Callable。
button.connect("button_down", _on_button_down)
# 选项 2:Object.connect() 并使用由目标对象和方法名称构造的 Callable。
button.connect("button_down", Callable(self, "_on_button_down"))
# 选项 3:Signal.connect() 并使用已定义的函数的隐式 Callable。
button.button_down.connect(_on_button_down)
# 选项 4:Signal.connect() 并使用由目标对象和方法名称构造的 Callable。
button.button_down.connect(Callable(self, "_on_button_down"))
func _on_button_down():
print("按钮按下!")
public override void _Ready()
{
var button = new Button();
// 选项 1:在 C# 中,我们可以将信号用作事件并使用以下惯用语法进行连接:
button.ButtonDown += OnButtonDown;
// 选项 2:GodotObject.Connect() 并使用从方法组构造的 Callable。
button.Connect(Button.SignalName.ButtonDown, Callable.From(OnButtonDown));
// 选项 3:GodotObject.Connect() 并使用由目标对象和方法名称构造的 Callable。
button.Connect(Button.SignalName.ButtonDown, new Callable(this, MethodName.OnButtonDown));
}
private void OnButtonDown()
{
GD.Print("按钮按下!");
}
虽然所有选项都有相同的结果(button
的 BaseButton.button_down 信号将被连接到 _on_button_down
),但选项 3 提供了最好的验证:如果 button_down
Signal 或 _on_button_down
Callable 没有被定义,它将打印一个编译时错误。另一方面,选项 2 只依赖于字符串名称,并且只能在运行时验证这两个名称:如果 "button_down"
不对应于一个信号,或者如果 "_on_button_down"
不是对象 self
中的注册方法,它将打印一个运行时错误。使用选项 1、2 或 4 的主要原因,是你是否确实需要使用字符串(例如,根据从配置文件读取的字符串,以编程的方式连接信号)。否则,选项 3 是推荐的(也是最快的)方法。
绑定和传递参数:
绑定参数的语法是通过 Callable.bind,它返回一个绑定了参数的 Callable 的副本。
当调用 emit_signal 或 Signal.emit 时,信号参数也可以被传递。下面的示例显示了这些信号参数和绑定参数之间的关系。
func _ready():
# 这假设存在一个 `Player` 类,它定义了一个 `hit` 信号。
var player = Player.new()
# 使用 Callable.bind()。
player.hit.connect(_on_player_hit.bind("剑", 100))
# 发出信号时添加的参数首先被传递。
player.hit.emit("黑暗领主", 5)
# 我们在发出时传递两个参数(`hit_by`,`level`),
# 并在连接时再绑定两个参数(`weapon_type`、`damage`)。
func _on_player_hit(hit_by, level, weapon_type, damage):
print("被 %s(等级 %d)用武器 %s 击中,造成 %d 伤害。" % [hit_by, level, weapon_type, damage])
public override void _Ready()
{
// 这假设存在一个 `Player` 类,它定义了一个 `Hit` 信号。
var player = new Player();
// 使用 lambda 表达式创建一个闭包来捕获额外的参数。
// lambda 仅接收由信号委托定义的参数。
player.Hit += (hitBy, level) => OnPlayerHit(hitBy, level, "剑", 100);
// 发出信号时添加的参数首先被传递。
player.EmitSignal(SignalName.Hit, "黑暗领主", 5);
}
// 我们在发出时传递两个参数(`hit_by`,`level`),
// 并在连接时再绑定两个参数(`weapon_type`、`damage`)。
private void OnPlayerHit(string hitBy, int level, string weaponType, int damage)
{
GD.Print($"被 {hitBy}(等级 {level})用武器 {weaponType} 击中,造成 {damage} 伤害。");
}
void disconnect(signal: StringName, callable: Callable) 🔗
按名称从给定的 callable
断开 signal
。如果连接不存在,则生成一个错误。使用 is_connected 确保该连接存在。
Error emit_signal(signal: StringName, ...) vararg 🔗
按名称发出给定的 signal
。该信号必须存在,所以它应该是该类或其继承类之一的内置信号,或者是用户定义的信号(参见 add_user_signal)。该方法支持可变数量的参数,所以参数可以以逗号分隔的列表形式传递。
如果 signal
不存在或参数无效,则返回 @GlobalScope.ERR_UNAVAILABLE。
emit_signal("hit", "剑", 100)
emit_signal("game_over")
EmitSignal(SignalName.Hit, "剑", 100);
EmitSignal(SignalName.GameOver);
注意:在C#中,在引用内置 Godot 信号时,signal
必须是 snake_case。最好使用 SignalName
类中公开的名称,以避免在每次调用时分配一个新的 StringName。
void free() 🔗
从内存中删除该对象。对该对象的预先存在的引用会变得无效,并且任何访问它们的尝试都将会产生一个运行时错误。使用 @GlobalScope.is_instance_valid 检查引用时将返回 false
。
Variant get(property: StringName) const 🔗
返回给定 property
的 Variant 值。如果 property
不存在,则该方法返回 null
。
var node = Node2D.new()
node.rotation = 1.5
var a = node.get("rotation") # a 为 1.5
var node = new Node2D();
node.Rotation = 1.5f;
var a = node.Get(Node2D.PropertyName.Rotation); // a 为 1.5
注意:在 C# 中,在引用 Godot 内置属性时,property
必须是 snake_case。最好使用 PropertyName
类中公开的名称,以避免在每次调用时分配一个新的 StringName。
返回该对象的内置类名,作为一个 String。另请参阅 is_class。
注意:该方法将忽略 class_name
声明。如果该对象的脚本定义了一个 class_name
,则改为返回内置基类名称。
Array[Dictionary] get_incoming_connections() const 🔗
返回该对象接收到的信号连接的 Array。每个连接都被表示为包含三个条目的 Dictionary:
signal
是对 Signal 的引用;callable
是对 Callable 的引用;flags
是 ConnectFlags 的组合。
Variant get_indexed(property_path: NodePath) const 🔗
获取该对象的某个属性,该属性的属性路径由 property_path
给出。该路径应该是相对于当前对象的 NodePath,可是使用英文冒号(:
)访问内嵌属性。
示例:"position:x"
或 "material:next_pass:blend_mode"
。
var node = Node2D.new()
node.position = Vector2(5, -10)
var a = node.get_indexed("position") # a 为 Vector2(5, -10)
var b = node.get_indexed("position:y") # b 为 -10
var node = new Node2D();
node.Position = new Vector2(5, -10);
var a = node.GetIndexed("position"); // a 为 Vector2(5, -10)
var b = node.GetIndexed("position:y"); // b 为 -10
注意:在 C# 中引用内置 Godot 属性时 property_path
必须为 snake_case 蛇形大小写。请优先使用 PropertyName
类中暴露的名称,避免每次调用都重新分配一个 StringName。
注意:这个方法不支持指向 SceneTree 中节点的路径,仅支持子属性路径。在节点语境下,请改用 Node.get_node_and_resource。
返回该对象的唯一实例 ID。该 ID 可以保存在 EncodedObjectAsID 中,通过 @GlobalScope.instance_from_id 可以检索到对应的对象实例。
注意:该 ID 仅在当前会话中有意义:通过网络传输后并不对应相同的对象,隔段时间后从文件中加载亦然。
Variant get_meta(name: StringName, default: Variant = null) const 🔗
返回该对象的元数据中名称为 name
的条目。如果不存在该条目,则返回 default
。如果 default
为 null
,则还会生成错误。
注意:元数据的名称必须是符合 StringName.is_valid_identifier 的有效标识符。
注意:名称以下划线(_
)开头的元数据仅供编辑器使用。仅供编辑器使用的元数据不会在“检查器”中显示,虽然仍然能够被这个方法找到,但是不应该进行编辑。
Array[StringName] get_meta_list() const 🔗
Returns the object's metadata entry names as an Array of StringNames.
int get_method_argument_count(method: StringName) const 🔗
根据名称返回给定 method
的参数数量。
注意:在 C# 中引用内置 Godot 方法时,method
必须采用 snake_case 蛇形命名法。请优先使用 MethodName
类中公开的名称,以避免在每次调用时分配一个新的 StringName。
Array[Dictionary] get_method_list() const 🔗
将该对象的方法及对应签名作为字典 Array 返回。每个 Dictionary 包含以下条目:
-name
是该方法的名称,为 String;
-args
是代表参数的字典 Array;
-default_args
是默认参数,为变体 Array;
-flags
是 MethodFlags 的组合;
-id
是该方法的内部标识符 int;
-return
是返回值,为 Dictionary;
注意:args
和 return
的字典格式与 get_property_list 的结果相同,但不会用到所有条目。
Array[Dictionary] get_property_list() const 🔗
以字典 Array 的形式返回该对象的属性列表。每个 Dictionary 中都包含如下条目:
name
是该属性的名称,类型为 String;class_name
为空 StringName,除非该属性为 @GlobalScope.TYPE_OBJECT 并继承自某个类;type
是该属性的类型,类型为 int(见 Variant.Type);hint
是应当如何编辑该属性(见 PropertyHint);hint_string
取决于 hint(见 PropertyHint);usage
是 PropertyUsageFlags 的组合。
注意:在 GDScript 中,类的所有成员都被视为属性。在 C# 和 GDExtension 中,则需要使用装饰器或特性将类的成员显式标记为 Godot 属性。
返回该对象的 Script 实例,如果没有附加脚本,则返回 null
。
Array[Dictionary] get_signal_connection_list(signal: StringName) const 🔗
返回给定 signal
名称的连接的 Array。每个连接都被表示为包含三个条目的 Dictionary:
signal
是对 Signal 的引用;callable
是对已连接 Callable 的引用;flags
是 ConnectFlags 的组合。
Array[Dictionary] get_signal_list() const 🔗
将现有信号的列表返回为字典的一个 Array 。
注意:由于该实现,每个 Dictionary 被格式为与 get_method_list 的返回值非常相似。
StringName get_translation_domain() const 🔗
Returns the name of the translation domain used by tr and tr_n. See also TranslationServer.
bool has_connections(signal: StringName) const 🔗
Returns true
if any connection exists on the given signal
name.
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.
bool has_meta(name: StringName) const 🔗
如果找到名称为 name
的元数据条目,则返回 true
。另请参阅 get_meta、set_meta 和 remove_meta。
注意:元数据的名称必须是符合 StringName.is_valid_identifier 的有效标识符。
注意:名称以下划线(_
)开头的元数据仅供编辑器使用。仅供编辑器使用的元数据不会在“检查器”中显示,虽然仍然能够被这个方法找到,但是不应该进行编辑。
bool has_method(method: StringName) const 🔗
如果该对象中存在给定的方法名 method
,则返回 true
。
注意:在 C# 中引用内置 Godot 方法时 method
必须为 snake_case 蛇形大小写。请优先使用 MethodName
类中暴露的名称,避免每次调用都重新分配一个 StringName。
bool has_signal(signal: StringName) const 🔗
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 signals. Prefer using the names exposed in the SignalName
class to avoid allocating a new StringName on each call.
bool has_user_signal(signal: StringName) const 🔗
如果存在给定的用户定义信号名称 signal
,则返回 true
。仅包含通过 add_user_signal 添加的信号。另见 remove_user_signal。
bool is_blocking_signals() const 🔗
如果该对象正在阻止发出信号,则返回 true
。见 set_block_signals。
bool is_class(class: String) const 🔗
如果该对象继承自给定的 class
则返回 true
。另见 get_class。
var sprite2d = Sprite2D.new()
sprite2d.is_class("Sprite2D") # 返回 true
sprite2d.is_class("Node") # 返回 true
sprite2d.is_class("Node3D") # 返回 false
var sprite2D = new Sprite2D();
sprite2D.IsClass("Sprite2D"); // 返回 true
sprite2D.IsClass("Node"); // 返回 true
sprite2D.IsClass("Node3D"); // 返回 false
注意:此方法忽略对象脚本中的 class_name
声明。
bool is_connected(signal: StringName, callable: Callable) const 🔗
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 signals. Prefer using the names exposed in the SignalName
class to avoid allocating a new StringName on each call.
bool is_queued_for_deletion() const 🔗
如果为该对象调用了 Node.queue_free 方法,则返回 true
。
void notification(what: int, reversed: bool = false) 🔗
将给定的 what
通知发送给对象继承的所有类,触发对 _notification 的调用,从最高祖先(Object 类)开始,向下一直到对象的脚本。
如果 reversed
为 true
,则调用顺序会被颠倒。
var player = Node2D.new()
player.set_script(load("res://player.gd"))
player.notification(NOTIFICATION_ENTER_TREE)
# 调用顺序是 Object -> Node -> Node2D -> player.gd。
player.notification(NOTIFICATION_ENTER_TREE, true)
# 调用顺序是 player.gd -> Node2D -> Node -> Object。
var player = new Node2D();
player.SetScript(GD.Load("res://player.gd"));
player.Notification(NotificationEnterTree);
// 调用顺序是 GodotObject -> Node -> Node2D -> player.gd。
player.Notification(NotificationEnterTree, true);
// 调用顺序是 player.gd -> Node2D -> Node -> GodotObject。
void notify_property_list_changed() 🔗
发出 property_list_changed 信号。这主要是用来刷新编辑器,以让检查器和编辑器插件被正确更新。
bool property_can_revert(property: StringName) const 🔗
如果给定的属性 property
有自定义的默认值,则返回 true
。请使用 property_get_revert 获取 property
的默认值。
注意:“检查器”面板会使用这个方法来显示恢复图标。该对象必须实现 _property_can_revert 来自定义默认值。如果未实现 _property_can_revert,则这个方法返回 false
。
Variant property_get_revert(property: StringName) const 🔗
返回给定的属性 property
的自定义默认值。请使用 property_can_revert 检查 property
是否有自定义的默认值。
注意:“检查器”面板会使用这个方法来显示恢复图标。该对象必须实现 _property_get_revert 来自定义默认值。如果未实现 _property_get_revert,则这个方法返回 null
。
void remove_meta(name: StringName) 🔗
从对象的元数据中移除名称为 name
的条目。另请参阅 has_meta、get_meta 和 set_meta。
注意:元数据的名称必须是符合 StringName.is_valid_identifier 的有效标识符。
注意:名称以下划线(_
)开头的元数据仅供编辑器使用。仅供编辑器使用的元数据不会在“检查器”中显示,虽然仍然能够被这个方法找到,但是不应该进行编辑。
void remove_user_signal(signal: StringName) 🔗
从对象中移除给定的用户信号 signal
。另请参阅 add_user_signal 和 has_user_signal。
void set(property: StringName, value: 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 = Node2D.new()
node.set("global_scale", Vector2(8, 2.5))
print(node.global_scale) # Prints (8.0, 2.5)
var node = new Node2D();
node.Set(Node2D.PropertyName.GlobalScale, new Vector2(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 the PropertyName
class to avoid allocating a new StringName on each call.
void set_block_signals(enable: bool) 🔗
如果设置为 true
,这该对象将无法发出信号。因此,emit_signal 和信号连接将不起作用,直到该属性被设置为 false
。
void set_deferred(property: StringName, value: Variant) 🔗
在当前帧的末尾,将给定属性 property
的值分配为 value
。等价于通过 call_deferred 调用 set。
var node = Node2D.new()
add_child(node)
node.rotation = 1.5
node.set_deferred("rotation", 3.0)
print(node.rotation) # 输出 1.5
await get_tree().process_frame
print(node.rotation) # 输出 3.0
var node = new Node2D();
node.Rotation = 1.5f;
node.SetDeferred(Node2D.PropertyName.Rotation, 3f);
GD.Print(node.Rotation); // 输出 1.5
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
GD.Print(node.Rotation); // 输出 3.0
注意:在 C# 中引用内置 Godot 属性时 property
必须为 snake_case 蛇形大小写。请优先使用 PropertyName
类中暴露的名称,避免每次调用都重新分配一个 StringName。
void set_indexed(property_path: NodePath, value: Variant) 🔗
Assigns a new value
to the property identified by the property_path
. The path should be a NodePath relative to this object, and can use the colon character (:
) to access nested properties.
var node = Node2D.new()
node.set_indexed("position", Vector2(42, 0))
node.set_indexed("position:y", -10)
print(node.position) # Prints (42.0, -10.0)
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#, property_path
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.
void set_message_translation(enable: bool) 🔗
如果设置为 true
,则允许对象使用 tr 和 tr_n 翻译消息。该属性默认启用。另请参阅 can_translate_messages。
void set_meta(name: StringName, value: Variant) 🔗
添加或更改对象元数据中名称为 name
的条目。元数据值 value
可以是任何 Variant,尽管某些类型无法正确序列化。
如果 value
为 null
,则该条目被移除。等价于使用 remove_meta。另见 has_meta 和 get_meta。
注意:元数据的名称必须是符合 StringName.is_valid_identifier 的有效标识符。
注意:名称以下划线(_
)开头的元数据仅供编辑器使用。仅供编辑器使用的元数据不会在“检查器”中显示,虽然仍然能够被这个方法找到,但是不应该进行编辑。
void set_script(script: Variant) 🔗
将脚本 script
附加至该对象,并进行实例化。因此会调用该脚本的 _init。Script 可用于扩展对象的功能。
如果已存在脚本,则该脚本的实例会被分离,其属性值和状态会丢失。仍会保留内置属性的值。
void set_translation_domain(domain: StringName) 🔗
Sets the name of the translation domain used by tr and tr_n. See also TranslationServer.
返回表示对象的 String。默认为 "<ClassName#RID>"
。覆盖 _to_string 以自定义对象的字符串表示形式。
String tr(message: StringName, context: StringName = &"") const 🔗
使用项目设置中配置的翻译目录,翻译一个 message
。可以进一步指定 context
来帮助翻译。请注意,大多数 Control 节点会自动翻译其字符串,因此该方法最适用于格式化的字符串或自定义绘制的文本。
如果 can_translate_messages 为 false
,或者没有翻译可用,则该方法将返回 message
而不做任何更改。请参阅 set_message_translation。
有关详细示例,请参阅《国际化游戏》。
注意:如果没有 Object 实例,则无法使用该方法,因为它需要 can_translate_messages 方法。要在静态上下文中翻译字符串,请使用 TranslationServer.translate。
String tr_n(message: StringName, plural_message: StringName, n: int, context: StringName = &"") const 🔗
使用项目设置中配置的翻译目录,翻译一个 message
或 plural_message
。可以进一步指定 context
来帮助翻译。
如果 can_translate_messages 为 false
,或者没有翻译可用,则该方法将返回 message
或 plural_message
,而不做任何更改。请参阅 set_message_translation。
n
是消息主题的数字或数量。它被翻译系统用来获取当前语言的正确复数形式。
有关详细示例,请参阅《使用 gettext 进行本地化》。
注意:负数和 float 数字可能不适用于某些可数科目。建议使用 tr 处理这些情况。
注意:如果没有 Object 实例,则无法使用该方法,因为它需要 can_translate_messages 方法。要在静态上下文中翻译字符串,请使用 TranslationServer.translate_plural。