mirror of
https://github.com/godotengine/godot-docs-l10n.git
synced 2025-12-31 09:49:22 +03:00
1805 lines
126 KiB
ReStructuredText
1805 lines
126 KiB
ReStructuredText
:github_url: hide
|
||
|
||
.. _class_Object:
|
||
|
||
Object
|
||
======
|
||
|
||
**Наследуется от:** :ref:`AudioServer<class_AudioServer>`, :ref:`CameraServer<class_CameraServer>`, :ref:`ClassDB<class_ClassDB>`, :ref:`DisplayServer<class_DisplayServer>`, :ref:`EditorFileSystemDirectory<class_EditorFileSystemDirectory>`, :ref:`EditorInterface<class_EditorInterface>`, :ref:`EditorPaths<class_EditorPaths>`, :ref:`EditorSelection<class_EditorSelection>`, :ref:`EditorUndoRedoManager<class_EditorUndoRedoManager>`, :ref:`EditorVCSInterface<class_EditorVCSInterface>`, :ref:`Engine<class_Engine>`, :ref:`EngineDebugger<class_EngineDebugger>`, :ref:`FramebufferCacheRD<class_FramebufferCacheRD>`, :ref:`GDExtensionManager<class_GDExtensionManager>`, :ref:`Geometry2D<class_Geometry2D>`, :ref:`Geometry3D<class_Geometry3D>`, :ref:`GodotInstance<class_GodotInstance>`, :ref:`Input<class_Input>`, :ref:`InputMap<class_InputMap>`, :ref:`IP<class_IP>`, :ref:`JavaClassWrapper<class_JavaClassWrapper>`, :ref:`JavaScriptBridge<class_JavaScriptBridge>`, :ref:`JNISingleton<class_JNISingleton>`, :ref:`JSONRPC<class_JSONRPC>`, :ref:`MainLoop<class_MainLoop>`, :ref:`Marshalls<class_Marshalls>`, :ref:`MovieWriter<class_MovieWriter>`, :ref:`NativeMenu<class_NativeMenu>`, :ref:`NavigationMeshGenerator<class_NavigationMeshGenerator>`, :ref:`NavigationServer2D<class_NavigationServer2D>`, :ref:`NavigationServer2DManager<class_NavigationServer2DManager>`, :ref:`NavigationServer3D<class_NavigationServer3D>`, :ref:`NavigationServer3DManager<class_NavigationServer3DManager>`, :ref:`Node<class_Node>`, :ref:`OpenXRExtensionWrapper<class_OpenXRExtensionWrapper>`, :ref:`OpenXRInteractionProfileMetadata<class_OpenXRInteractionProfileMetadata>`, :ref:`OS<class_OS>`, :ref:`Performance<class_Performance>`, :ref:`PhysicsDirectBodyState2D<class_PhysicsDirectBodyState2D>`, :ref:`PhysicsDirectBodyState3D<class_PhysicsDirectBodyState3D>`, :ref:`PhysicsDirectSpaceState2D<class_PhysicsDirectSpaceState2D>`, :ref:`PhysicsDirectSpaceState3D<class_PhysicsDirectSpaceState3D>`, :ref:`PhysicsServer2D<class_PhysicsServer2D>`, :ref:`PhysicsServer2DManager<class_PhysicsServer2DManager>`, :ref:`PhysicsServer3D<class_PhysicsServer3D>`, :ref:`PhysicsServer3DManager<class_PhysicsServer3DManager>`, :ref:`PhysicsServer3DRenderingServerHandler<class_PhysicsServer3DRenderingServerHandler>`, :ref:`ProjectSettings<class_ProjectSettings>`, :ref:`RefCounted<class_RefCounted>`, :ref:`RenderData<class_RenderData>`, :ref:`RenderingDevice<class_RenderingDevice>`, :ref:`RenderingServer<class_RenderingServer>`, :ref:`RenderSceneData<class_RenderSceneData>`, :ref:`ResourceLoader<class_ResourceLoader>`, :ref:`ResourceSaver<class_ResourceSaver>`, :ref:`ResourceUID<class_ResourceUID>`, :ref:`ScriptLanguage<class_ScriptLanguage>`, :ref:`ShaderIncludeDB<class_ShaderIncludeDB>`, :ref:`TextServerManager<class_TextServerManager>`, :ref:`ThemeDB<class_ThemeDB>`, :ref:`TileData<class_TileData>`, :ref:`Time<class_Time>`, :ref:`TranslationServer<class_TranslationServer>`, :ref:`TreeItem<class_TreeItem>`, :ref:`UndoRedo<class_UndoRedo>`, :ref:`UniformSetCacheRD<class_UniformSetCacheRD>`, :ref:`WorkerThreadPool<class_WorkerThreadPool>`, :ref:`XRServer<class_XRServer>`, :ref:`XRVRS<class_XRVRS>`
|
||
|
||
Базовый класс для всех остальных классов в движке.
|
||
|
||
.. rst-class:: classref-introduction-group
|
||
|
||
Описание
|
||
----------------
|
||
|
||
Расширенный тип :ref:`Variant<class_Variant>`. Все классы в движке наследуются от Object. Каждый класс может определять новые свойства, методы или сигналы, которые доступны всем наследующим классам. Например, экземпляр :ref:`Sprite2D<class_Sprite2D>` может вызывать :ref:`Node.add_child()<class_Node_method_add_child>`, поскольку он наследуется от :ref:`Node<class_Node>`.
|
||
|
||
Вы можете создавать новые экземпляры, используя ``Object.new()`` в GDScript или ``new GodotObject`` в C#.
|
||
|
||
Чтобы удалить экземпляр Object, вызовите :ref:`free()<class_Object_method_free>`. Это необходимо для большинства классов, наследующих Object, поскольку они не управляют памятью самостоятельно и в противном случае вызовут утечки памяти, если больше не используются. Есть несколько классов, которые выполняют управление памятью. Например, :ref:`RefCounted<class_RefCounted>` (и, соответственно, :ref:`Resource<class_Resource>`) удаляет себя, когда на него больше не ссылаются, а :ref:`Node<class_Node>` удаляет своих дочерних элементов при освобождении.
|
||
|
||
К объектам может быть прикреплен :ref:`Script<class_Script>`. После создания экземпляра :ref:`Script<class_Script>` он фактически действует как расширение базового класса, позволяя ему определять и наследовать новые свойства, методы и сигналы.
|
||
|
||
Внутри :ref:`Script<class_Script>` :ref:`_get_property_list()<class_Object_private_method__get_property_list>` может быть переопределен для настройки свойств несколькими способами. Это позволяет им быть доступными для редактора, отображаться в виде списков параметров, подразделяться на группы, сохранять на диске и т. д. Скриптовые языки предлагают более простые способы настройки свойств, например, с помощью аннотации :ref:`@GDScript.@export<class_@GDScript_annotation_@export>`.
|
||
|
||
Godot очень динамичен. Скрипт объекта, а следовательно, и его свойства, методы и сигналы, могут быть изменены во время выполнения. Из-за этого могут быть случаи, когда, например, свойство, требуемое методом, может не существовать. Чтобы предотвратить ошибки времени выполнения, см. такие методы, как :ref:`set()<class_Object_method_set>`, :ref:`get()<class_Object_method_get>`, :ref:`call()<class_Object_method_call>`, :ref:`has_method()<class_Object_method_has_method>`, :ref:`has_signal()<class_Object_method_has_signal>` и т. д. Обратите внимание, что эти методы **намного** медленнее прямых ссылок.
|
||
|
||
В GDScript вы также можете проверить, существует ли заданное свойство, метод или имя сигнала в объекте с помощью оператора ``in``:
|
||
|
||
::
|
||
|
||
var node = Node.new()
|
||
print("name" in node) # Выводит true
|
||
print("get_parent" in node) # Выводит true
|
||
print("tree_entered" in node) # Выводит true
|
||
print("unknown" in node) # Выводит false
|
||
|
||
Уведомления — это константы :ref:`int<class_int>`, которые обычно отправляются и принимаются объектами. Например, на каждом отрисованном кадре :ref:`SceneTree<class_SceneTree>` уведомляет узлы внутри дерева с помощью :ref:`Node.NOTIFICATION_PROCESS<class_Node_constant_NOTIFICATION_PROCESS>`. Узлы получают его и могут вызывать :ref:`Node._process()<class_Node_private_method__process>` для обновления. Чтобы использовать уведомления, см. :ref:`notification()<class_Object_method_notification>` и :ref:`_notification()<class_Object_private_method__notification>`.
|
||
|
||
Наконец, каждый объект также может содержать метаданные (данные о данных). :ref:`set_meta()<class_Object_method_set_meta>` может быть полезен для хранения информации, от которой сам объект не зависит. Чтобы сохранить чистоту кода, не рекомендуется чрезмерно использовать метаданные.
|
||
|
||
\ **Примечание:** В отличие от ссылок на :ref:`RefCounted<class_RefCounted>`, ссылки на объект, хранящийся в переменной, могут стать недействительными, не будучи установленными в ``null``. Чтобы проверить, был ли объект удален, *не* сравнивайте его с ``null``. Вместо этого используйте :ref:`@GlobalScope.is_instance_valid()<class_@GlobalScope_method_is_instance_valid>`. Также рекомендуется наследовать от :ref:`RefCounted<class_RefCounted>` для классов, хранящих данные вместо **Object**.
|
||
|
||
\ **Примечание:** ``script`` не отображается, как большинство свойств. Чтобы задать или получить :ref:`Script<class_Script>` объекта в коде, используйте :ref:`set_script()<class_Object_method_set_script>` и :ref:`get_script()<class_Object_method_get_script>` соответственно.
|
||
|
||
\ **Примечание:** В булевом контексте **Object** будет оцениваться как ``false``, если он равен ``null`` или был освобожден. В противном случае **Object** всегда будет оцениваться как ``true``. См. также :ref:`@GlobalScope.is_instance_valid()<class_@GlobalScope_method_is_instance_valid>`.
|
||
|
||
.. rst-class:: classref-introduction-group
|
||
|
||
Обучающие материалы
|
||
--------------------------------------
|
||
|
||
- :doc:`Введение класса объекта <../engine_details/architecture/object_class>`
|
||
|
||
- :doc:`Когда и как избегать использования узлов для всего <../tutorials/best_practices/node_alternatives>`
|
||
|
||
- :doc:`Уведомления объекта <../tutorials/best_practices/godot_notifications>`
|
||
|
||
.. rst-class:: classref-reftable-group
|
||
|
||
Методы
|
||
------------
|
||
|
||
.. table::
|
||
:widths: auto
|
||
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`_get<class_Object_private_method__get>`\ (\ property\: :ref:`StringName<class_StringName>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] | :ref:`_get_property_list<class_Object_private_method__get_property_list>`\ (\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`_init<class_Object_private_method__init>`\ (\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`_iter_get<class_Object_private_method__iter_get>`\ (\ iter\: :ref:`Variant<class_Variant>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`_iter_init<class_Object_private_method__iter_init>`\ (\ iter\: :ref:`Array<class_Array>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`_iter_next<class_Object_private_method__iter_next>`\ (\ iter\: :ref:`Array<class_Array>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`_notification<class_Object_private_method__notification>`\ (\ what\: :ref:`int<class_int>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`_property_can_revert<class_Object_private_method__property_can_revert>`\ (\ property\: :ref:`StringName<class_StringName>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`_property_get_revert<class_Object_private_method__property_get_revert>`\ (\ property\: :ref:`StringName<class_StringName>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`_set<class_Object_private_method__set>`\ (\ property\: :ref:`StringName<class_StringName>`, value\: :ref:`Variant<class_Variant>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`_to_string<class_Object_private_method__to_string>`\ (\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`_validate_property<class_Object_private_method__validate_property>`\ (\ property\: :ref:`Dictionary<class_Dictionary>`\ ) |virtual| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`add_user_signal<class_Object_method_add_user_signal>`\ (\ signal\: :ref:`String<class_String>`, arguments\: :ref:`Array<class_Array>` = []\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`call<class_Object_method_call>`\ (\ method\: :ref:`StringName<class_StringName>`, ...\ ) |vararg| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`call_deferred<class_Object_method_call_deferred>`\ (\ method\: :ref:`StringName<class_StringName>`, ...\ ) |vararg| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`callv<class_Object_method_callv>`\ (\ method\: :ref:`StringName<class_StringName>`, arg_array\: :ref:`Array<class_Array>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`can_translate_messages<class_Object_method_can_translate_messages>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`cancel_free<class_Object_method_cancel_free>`\ (\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`connect<class_Object_method_connect>`\ (\ signal\: :ref:`StringName<class_StringName>`, callable\: :ref:`Callable<class_Callable>`, flags\: :ref:`int<class_int>` = 0\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`disconnect<class_Object_method_disconnect>`\ (\ signal\: :ref:`StringName<class_StringName>`, callable\: :ref:`Callable<class_Callable>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Error<enum_@GlobalScope_Error>` | :ref:`emit_signal<class_Object_method_emit_signal>`\ (\ signal\: :ref:`StringName<class_StringName>`, ...\ ) |vararg| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`free<class_Object_method_free>`\ (\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`get<class_Object_method_get>`\ (\ property\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`get_class<class_Object_method_get_class>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] | :ref:`get_incoming_connections<class_Object_method_get_incoming_connections>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`get_indexed<class_Object_method_get_indexed>`\ (\ property_path\: :ref:`NodePath<class_NodePath>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_instance_id<class_Object_method_get_instance_id>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`get_meta<class_Object_method_get_meta>`\ (\ name\: :ref:`StringName<class_StringName>`, default\: :ref:`Variant<class_Variant>` = null\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Array<class_Array>`\[:ref:`StringName<class_StringName>`\] | :ref:`get_meta_list<class_Object_method_get_meta_list>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`int<class_int>` | :ref:`get_method_argument_count<class_Object_method_get_method_argument_count>`\ (\ method\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] | :ref:`get_method_list<class_Object_method_get_method_list>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] | :ref:`get_property_list<class_Object_method_get_property_list>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`get_script<class_Object_method_get_script>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] | :ref:`get_signal_connection_list<class_Object_method_get_signal_connection_list>`\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] | :ref:`get_signal_list<class_Object_method_get_signal_list>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`StringName<class_StringName>` | :ref:`get_translation_domain<class_Object_method_get_translation_domain>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`has_connections<class_Object_method_has_connections>`\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`has_meta<class_Object_method_has_meta>`\ (\ name\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`has_method<class_Object_method_has_method>`\ (\ method\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`has_signal<class_Object_method_has_signal>`\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`has_user_signal<class_Object_method_has_user_signal>`\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`is_blocking_signals<class_Object_method_is_blocking_signals>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`is_class<class_Object_method_is_class>`\ (\ class\: :ref:`String<class_String>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`is_connected<class_Object_method_is_connected>`\ (\ signal\: :ref:`StringName<class_StringName>`, callable\: :ref:`Callable<class_Callable>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`is_queued_for_deletion<class_Object_method_is_queued_for_deletion>`\ (\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`notification<class_Object_method_notification>`\ (\ what\: :ref:`int<class_int>`, reversed\: :ref:`bool<class_bool>` = false\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`notify_property_list_changed<class_Object_method_notify_property_list_changed>`\ (\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`bool<class_bool>` | :ref:`property_can_revert<class_Object_method_property_can_revert>`\ (\ property\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`Variant<class_Variant>` | :ref:`property_get_revert<class_Object_method_property_get_revert>`\ (\ property\: :ref:`StringName<class_StringName>`\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`remove_meta<class_Object_method_remove_meta>`\ (\ name\: :ref:`StringName<class_StringName>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`remove_user_signal<class_Object_method_remove_user_signal>`\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`set<class_Object_method_set>`\ (\ property\: :ref:`StringName<class_StringName>`, value\: :ref:`Variant<class_Variant>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`set_block_signals<class_Object_method_set_block_signals>`\ (\ enable\: :ref:`bool<class_bool>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`set_deferred<class_Object_method_set_deferred>`\ (\ property\: :ref:`StringName<class_StringName>`, value\: :ref:`Variant<class_Variant>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`set_indexed<class_Object_method_set_indexed>`\ (\ property_path\: :ref:`NodePath<class_NodePath>`, value\: :ref:`Variant<class_Variant>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`set_message_translation<class_Object_method_set_message_translation>`\ (\ enable\: :ref:`bool<class_bool>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`set_meta<class_Object_method_set_meta>`\ (\ name\: :ref:`StringName<class_StringName>`, value\: :ref:`Variant<class_Variant>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`set_script<class_Object_method_set_script>`\ (\ script\: :ref:`Variant<class_Variant>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| |void| | :ref:`set_translation_domain<class_Object_method_set_translation_domain>`\ (\ domain\: :ref:`StringName<class_StringName>`\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`to_string<class_Object_method_to_string>`\ (\ ) |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`tr<class_Object_method_tr>`\ (\ message\: :ref:`StringName<class_StringName>`, context\: :ref:`StringName<class_StringName>` = &""\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
| :ref:`String<class_String>` | :ref:`tr_n<class_Object_method_tr_n>`\ (\ message\: :ref:`StringName<class_StringName>`, plural_message\: :ref:`StringName<class_StringName>`, n\: :ref:`int<class_int>`, context\: :ref:`StringName<class_StringName>` = &""\ ) |const| |
|
||
+------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
||
|
||
.. rst-class:: classref-section-separator
|
||
|
||
----
|
||
|
||
.. rst-class:: classref-descriptions-group
|
||
|
||
Сигналы
|
||
--------------
|
||
|
||
.. _class_Object_signal_property_list_changed:
|
||
|
||
.. rst-class:: classref-signal
|
||
|
||
**property_list_changed**\ (\ ) :ref:`🔗<class_Object_signal_property_list_changed>`
|
||
|
||
Вызывается при вызове :ref:`notify_property_list_changed()<class_Object_method_notify_property_list_changed>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_signal_script_changed:
|
||
|
||
.. rst-class:: classref-signal
|
||
|
||
**script_changed**\ (\ ) :ref:`🔗<class_Object_signal_script_changed>`
|
||
|
||
Вызывается при изменении скрипта объекта.
|
||
|
||
\ **Примечание:** Когда вызывается этот сигнал, новый скрипт еще не инициализирован. Если вам нужно получить доступ к новому скрипту, отложите подключения к этому сигналу с помощью :ref:`CONNECT_DEFERRED<class_Object_constant_CONNECT_DEFERRED>`.
|
||
|
||
.. rst-class:: classref-section-separator
|
||
|
||
----
|
||
|
||
.. rst-class:: classref-descriptions-group
|
||
|
||
Перечисления
|
||
------------------------
|
||
|
||
.. _enum_Object_ConnectFlags:
|
||
|
||
.. rst-class:: classref-enumeration
|
||
|
||
enum **ConnectFlags**: :ref:`🔗<enum_Object_ConnectFlags>`
|
||
|
||
.. _class_Object_constant_CONNECT_DEFERRED:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ConnectFlags<enum_Object_ConnectFlags>` **CONNECT_DEFERRED** = ``1``
|
||
|
||
Отложенные соединения активируют свои :ref:`Callable<class_Callable>` во время простоя (в конце кадра), а не мгновенно.
|
||
|
||
.. _class_Object_constant_CONNECT_PERSIST:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ConnectFlags<enum_Object_ConnectFlags>` **CONNECT_PERSIST** = ``2``
|
||
|
||
Persisting connections are stored when the object is serialized (such as when using :ref:`PackedScene.pack()<class_PackedScene_method_pack>`). In the editor, connections created through the Signals dock are always persisting.
|
||
|
||
\ **Note:** Connections to lambda functions (that is, when the function code is embedded in the :ref:`connect()<class_Object_method_connect>` call) cannot be made persistent.
|
||
|
||
.. _class_Object_constant_CONNECT_ONE_SHOT:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ConnectFlags<enum_Object_ConnectFlags>` **CONNECT_ONE_SHOT** = ``4``
|
||
|
||
Одноразовые соединения автоматически отключаются после выброса.
|
||
|
||
.. _class_Object_constant_CONNECT_REFERENCE_COUNTED:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ConnectFlags<enum_Object_ConnectFlags>` **CONNECT_REFERENCE_COUNTED** = ``8``
|
||
|
||
Ссылки-подсчетные соединения могут быть назначены одному и тому же :ref:`Callable<class_Callable>` несколько раз. Каждое отключение уменьшает внутренний счетчик. Сигнал полностью отключается только тогда, когда счетчик достигает 0.
|
||
|
||
.. _class_Object_constant_CONNECT_APPEND_SOURCE_OBJECT:
|
||
|
||
.. rst-class:: classref-enumeration-constant
|
||
|
||
:ref:`ConnectFlags<enum_Object_ConnectFlags>` **CONNECT_APPEND_SOURCE_OBJECT** = ``16``
|
||
|
||
Исходный объект автоматически привязывается при создании экземпляра :ref:`PackedScene<class_PackedScene>`. Если этот флаговый бит включен, исходный объект будет добавлен сразу после исходных аргументов сигнала.
|
||
|
||
.. rst-class:: classref-section-separator
|
||
|
||
----
|
||
|
||
.. rst-class:: classref-descriptions-group
|
||
|
||
Константы
|
||
------------------
|
||
|
||
.. _class_Object_constant_NOTIFICATION_POSTINITIALIZE:
|
||
|
||
.. rst-class:: classref-constant
|
||
|
||
**NOTIFICATION_POSTINITIALIZE** = ``0`` :ref:`🔗<class_Object_constant_NOTIFICATION_POSTINITIALIZE>`
|
||
|
||
Уведомление получено при инициализации объекта, до присоединения его скрипта. Используется внутренне.
|
||
|
||
.. _class_Object_constant_NOTIFICATION_PREDELETE:
|
||
|
||
.. rst-class:: classref-constant
|
||
|
||
**NOTIFICATION_PREDELETE** = ``1`` :ref:`🔗<class_Object_constant_NOTIFICATION_PREDELETE>`
|
||
|
||
Notification received when the object is about to be deleted. Can be used like destructors in object-oriented programming languages.
|
||
|
||
This notification is sent in reversed order.
|
||
|
||
.. _class_Object_constant_NOTIFICATION_EXTENSION_RELOADED:
|
||
|
||
.. rst-class:: classref-constant
|
||
|
||
**NOTIFICATION_EXTENSION_RELOADED** = ``2`` :ref:`🔗<class_Object_constant_NOTIFICATION_EXTENSION_RELOADED>`
|
||
|
||
Уведомление получено, когда объект завершает горячую перезагрузку. Это уведомление отправляется только для классов расширений и производных.
|
||
|
||
.. rst-class:: classref-section-separator
|
||
|
||
----
|
||
|
||
.. rst-class:: classref-descriptions-group
|
||
|
||
Описания метода
|
||
------------------------------
|
||
|
||
.. _class_Object_private_method__get:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **_get**\ (\ property\: :ref:`StringName<class_StringName>`\ ) |virtual| :ref:`🔗<class_Object_private_method__get>`
|
||
|
||
Override this method to customize the behavior of :ref:`get()<class_Object_method_get>`. Should return the given ``property``'s value, or ``null`` if the ``property`` should be handled normally.
|
||
|
||
Combined with :ref:`_set()<class_Object_private_method__set>` and :ref:`_get_property_list()<class_Object_private_method__get_property_list>`, this method allows defining custom properties, which is particularly useful for editor plugins.
|
||
|
||
\ **Note:** This method is not called when getting built-in properties of an object, including properties defined with :ref:`@GDScript.@export<class_@GDScript_annotation_@export>`.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
func _get(property):
|
||
if property == "fake_property":
|
||
print("Getting my property!")
|
||
return 4
|
||
|
||
func _get_property_list():
|
||
return [
|
||
{ "name": "fake_property", "type": TYPE_INT }
|
||
]
|
||
|
||
.. code-tab:: csharp
|
||
|
||
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 },
|
||
},
|
||
];
|
||
}
|
||
|
||
|
||
|
||
\ **Note:** Unlike other virtual methods, this method is called automatically for every script that overrides it. This means that the base implementation should not be called via ``super`` in GDScript or its equivalents in other languages. The bottom-most sub-class will be called first, with subsequent calls ascending the class hierarchy. The call chain will stop on the first class that returns a non-``null`` value.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__get_property_list:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] **_get_property_list**\ (\ ) |virtual| :ref:`🔗<class_Object_private_method__get_property_list>`
|
||
|
||
Override this method to provide a custom list of additional properties to handle by the engine.
|
||
|
||
Should return a property list, as an :ref:`Array<class_Array>` of dictionaries. The result is added to the array of :ref:`get_property_list()<class_Object_method_get_property_list>`, and should be formatted in the same way. Each :ref:`Dictionary<class_Dictionary>` must at least contain the ``name`` and ``type`` entries.
|
||
|
||
You can use :ref:`_property_can_revert()<class_Object_private_method__property_can_revert>` and :ref:`_property_get_revert()<class_Object_private_method__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:
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
@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
|
||
|
||
.. code-tab:: csharp
|
||
|
||
[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 :ref:`@GDScript.@export<class_@GDScript_annotation_@export>`, :ref:`@GDScript.@export_enum<class_@GDScript_annotation_@export_enum>`, :ref:`@GDScript.@export_group<class_@GDScript_annotation_@export_group>`, etc. If you want to customize exported properties, use :ref:`_validate_property()<class_Object_private_method__validate_property>`.
|
||
|
||
\ **Note:** If the object's script is not :ref:`@GDScript.@tool<class_@GDScript_annotation_@tool>`, this method will not be called in the editor.
|
||
|
||
\ **Note:** Unlike other virtual methods, this method is called automatically for every script that overrides it. This means that the base implementation should not be called via ``super`` in GDScript or its equivalents in other languages. The bottom-most sub-class will be called first, with subsequent calls ascending the class hierarchy.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__init:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **_init**\ (\ ) |virtual| :ref:`🔗<class_Object_private_method__init>`
|
||
|
||
Вызывается при создании экземпляра скрипта объекта, часто после инициализации объекта в памяти (через ``Object.new()`` в GDScript или ``new GodotObject`` в C#). Он также может быть определен для приема параметров. Этот метод похож на конструктор в большинстве языков программирования.
|
||
|
||
\ **Примечание:** Если :ref:`_init()<class_Object_private_method__init>` определен с *обязательными* параметрами, объект со скриптом может быть создан только напрямую. Если используются любые другие средства (например, :ref:`PackedScene.instantiate()<class_PackedScene_method_instantiate>` или :ref:`Node.duplicate()<class_Node_method_duplicate>`), инициализация скрипта завершится ошибкой.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__iter_get:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **_iter_get**\ (\ iter\: :ref:`Variant<class_Variant>`\ ) |virtual| :ref:`🔗<class_Object_private_method__iter_get>`
|
||
|
||
Возвращает текущее итерируемое значение. ``iter`` сохраняет состояние итерации, но в отличие от :ref:`_iter_init()<class_Object_private_method__iter_init>` и :ref:`_iter_next()<class_Object_private_method__iter_next>` состояние должно быть доступно только для чтения, поэтому нет оболочки :ref:`Array<class_Array>`.
|
||
|
||
\ **Совет:** В GDScript вы можете использовать подтип :ref:`Variant<class_Variant>` в качестве возвращаемого типа для :ref:`_iter_get()<class_Object_private_method__iter_get>`. Указанный тип будет использоваться для установки типа переменной итератора в циклах ``for``, что повышает безопасность типов.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__iter_init:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **_iter_init**\ (\ iter\: :ref:`Array<class_Array>`\ ) |virtual| :ref:`🔗<class_Object_private_method__iter_init>`
|
||
|
||
Инициализирует итератор. ``iter`` сохраняет состояние итерации. Поскольку GDScript не поддерживает передачу аргументов по ссылке, в качестве оболочки используется одноэлементный массив. Возвращает ``true`` до тех пор, пока итератор не достигнет конца.
|
||
|
||
::
|
||
|
||
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) # Выводит 2, 3, 4.
|
||
|
||
\ **Примечание:** В качестве альтернативы вы можете игнорировать ``iter`` и вместо этого использовать состояние объекта, см. `online docs <../tutorials/scripting/gdscript/gdscript_advanced.html#custom-iterators>`__ для примера. Обратите внимание, что в этом случае вы не сможете повторно использовать один и тот же экземпляр итератора во вложенных циклах. Кроме того, убедитесь, что вы сбросили состояние итератора в этом методе, если вы хотите повторно использовать один и тот же экземпляр несколько раз.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__iter_next:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **_iter_next**\ (\ iter\: :ref:`Array<class_Array>`\ ) |virtual| :ref:`🔗<class_Object_private_method__iter_next>`
|
||
|
||
Перемещает итератор на следующую итерацию. ``iter`` сохраняет состояние итерации. Поскольку GDScript не поддерживает передачу аргументов по ссылке, в качестве оболочки используется одноэлементный массив. Возвращает ``true`` до тех пор, пока итератор не достигнет конца.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__notification:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **_notification**\ (\ what\: :ref:`int<class_int>`\ ) |virtual| :ref:`🔗<class_Object_private_method__notification>`
|
||
|
||
Called when the object receives a notification, which can be identified in ``what`` by comparing it with a constant. See also :ref:`notification()<class_Object_method_notification>`.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
func _notification(what):
|
||
if what == NOTIFICATION_PREDELETE:
|
||
print("Goodbye!")
|
||
|
||
.. code-tab:: csharp
|
||
|
||
public override void _Notification(int what)
|
||
{
|
||
if (what == NotificationPredelete)
|
||
{
|
||
GD.Print("Goodbye!");
|
||
}
|
||
}
|
||
|
||
|
||
|
||
\ **Note:** The base **Object** defines a few notifications (:ref:`NOTIFICATION_POSTINITIALIZE<class_Object_constant_NOTIFICATION_POSTINITIALIZE>` and :ref:`NOTIFICATION_PREDELETE<class_Object_constant_NOTIFICATION_PREDELETE>`). Inheriting classes such as :ref:`Node<class_Node>` define a lot more notifications, which are also received by this method.
|
||
|
||
\ **Note:** Unlike other virtual methods, this method is called automatically for every script that overrides it. This means that the base implementation should not be called via ``super`` in GDScript or its equivalents in other languages. Call order depends on the ``reversed`` argument of :ref:`notification()<class_Object_method_notification>` and varies between different notifications. Most notifications are sent in the forward order (i.e. Object class first, most derived class last).
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__property_can_revert:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **_property_can_revert**\ (\ property\: :ref:`StringName<class_StringName>`\ ) |virtual| :ref:`🔗<class_Object_private_method__property_can_revert>`
|
||
|
||
Override this method to customize the given ``property``'s revert behavior. Should return ``true`` if the ``property`` has a custom default value and is revertible in the Inspector dock. Use :ref:`_property_get_revert()<class_Object_private_method__property_get_revert>` to specify the ``property``'s default value.
|
||
|
||
\ **Note:** This method must return consistently, regardless of the current value of the ``property``.
|
||
|
||
\ **Note:** Unlike other virtual methods, this method is called automatically for every script that overrides it. This means that the base implementation should not be called via ``super`` in GDScript or its equivalents in other languages. The bottom-most sub-class will be called first, with subsequent calls ascending the class hierarchy. The call chain will stop on the first class that returns ``true``.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__property_get_revert:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **_property_get_revert**\ (\ property\: :ref:`StringName<class_StringName>`\ ) |virtual| :ref:`🔗<class_Object_private_method__property_get_revert>`
|
||
|
||
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:** :ref:`_property_can_revert()<class_Object_private_method__property_can_revert>` must also be overridden for this method to be called.
|
||
|
||
\ **Note:** Unlike other virtual methods, this method is called automatically for every script that overrides it. This means that the base implementation should not be called via ``super`` in GDScript or its equivalents in other languages. The bottom-most sub-class will be called first, with subsequent calls ascending the class hierarchy. The call chain will stop on the first class that returns a non-``null`` value.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__set:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **_set**\ (\ property\: :ref:`StringName<class_StringName>`, value\: :ref:`Variant<class_Variant>`\ ) |virtual| :ref:`🔗<class_Object_private_method__set>`
|
||
|
||
Override this method to customize the behavior of :ref:`set()<class_Object_method_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 :ref:`_get()<class_Object_private_method__get>` and :ref:`_get_property_list()<class_Object_private_method__get_property_list>`, this method allows defining custom properties, which is particularly useful for editor plugins.
|
||
|
||
\ **Note:** This method is not called when setting built-in properties of an object, including properties defined with :ref:`@GDScript.@export<class_@GDScript_annotation_@export>`.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
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 }
|
||
]
|
||
|
||
.. code-tab:: csharp
|
||
|
||
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 },
|
||
},
|
||
];
|
||
}
|
||
|
||
|
||
|
||
\ **Note:** Unlike other virtual methods, this method is called automatically for every script that overrides it. This means that the base implementation should not be called via ``super`` in GDScript or its equivalents in other languages. The bottom-most sub-class will be called first, with subsequent calls ascending the class hierarchy. The call chain will stop on the first class that returns ``true``.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__to_string:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **_to_string**\ (\ ) |virtual| :ref:`🔗<class_Object_private_method__to_string>`
|
||
|
||
Переопределите этот метод, чтобы настроить возвращаемое значение метода :ref:`to_string()<class_Object_method_to_string>` и, следовательно, представление объекта как :ref:`String<class_String>`.
|
||
|
||
::
|
||
|
||
func _to_string():
|
||
return "Welcome to Godot 4!"
|
||
|
||
func _init():
|
||
print(self) # Выводит "Welcome to Godot 4!"
|
||
var a = str(self) # a это "Welcome to Godot 4!"
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_private_method__validate_property:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **_validate_property**\ (\ property\: :ref:`Dictionary<class_Dictionary>`\ ) |virtual| :ref:`🔗<class_Object_private_method__validate_property>`
|
||
|
||
Переопределите этот метод, чтобы настроить существующие свойства. Каждая информация о свойствах проходит через этот метод, за исключением свойств, добавленных с помощью :ref:`_get_property_list()<class_Object_private_method__get_property_list>`. Содержимое словаря такое же, как в :ref:`_get_property_list()<class_Object_private_method__get_property_list>`.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
@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
|
||
|
||
.. code-tab:: csharp
|
||
|
||
[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;
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_add_user_signal:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **add_user_signal**\ (\ signal\: :ref:`String<class_String>`, arguments\: :ref:`Array<class_Array>` = []\ ) :ref:`🔗<class_Object_method_add_user_signal>`
|
||
|
||
Добавляет определяемый пользователем сигнал с именем ``signal``. Необязательные аргументы для сигнала могут быть добавлены как :ref:`Array<class_Array>` словарей, каждый из которых определяет ``name`` :ref:`String<class_String>` и ``type`` :ref:`int<class_int>` (см. :ref:`Variant.Type<enum_@GlobalScope_Variant.Type>`). См. также :ref:`has_user_signal()<class_Object_method_has_user_signal>` и :ref:`remove_user_signal()<class_Object_method_remove_user_signal>`.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
add_user_signal("hurt", [
|
||
{ "name": "damage", "type": TYPE_INT },
|
||
{ "name": "source", "type": TYPE_OBJECT }
|
||
])
|
||
|
||
.. code-tab:: csharp
|
||
|
||
AddUserSignal("Hurt",
|
||
[
|
||
new Godot.Collections.Dictionary()
|
||
{
|
||
{ "name", "damage" },
|
||
{ "type", (int)Variant.Type.Int },
|
||
},
|
||
new Godot.Collections.Dictionary()
|
||
{
|
||
{ "name", "source" },
|
||
{ "type", (int)Variant.Type.Object },
|
||
},
|
||
]);
|
||
|
||
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_call:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **call**\ (\ method\: :ref:`StringName<class_StringName>`, ...\ ) |vararg| :ref:`🔗<class_Object_method_call>`
|
||
|
||
Вызывает метод ``method`` для объекта и возвращает результат. Этот метод поддерживает переменное количество аргументов, поэтому параметры могут быть переданы в виде списка, разделенного запятыми.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
var node = Node3D.new()
|
||
node.call("rotate", Vector3(1.0, 0.0, 0.0), 1.571)
|
||
|
||
.. code-tab:: csharp
|
||
|
||
var node = new Node3D();
|
||
node.Call(Node3D.MethodName.Rotate, new Vector3(1f, 0f, 0f), 1.571f);
|
||
|
||
|
||
|
||
\ **Примечание:** В C# ``method`` должен быть в snake_case при ссылке на встроенные методы Godot. Предпочитайте использовать имена, представленные в классе ``MethodName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_call_deferred:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **call_deferred**\ (\ method\: :ref:`StringName<class_StringName>`, ...\ ) |vararg| :ref:`🔗<class_Object_method_call_deferred>`
|
||
|
||
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.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
var node = Node3D.new()
|
||
node.call_deferred("rotate", Vector3(1.0, 0.0, 0.0), 1.571)
|
||
|
||
.. code-tab:: csharp
|
||
|
||
var node = new Node3D();
|
||
node.CallDeferred(Node3D.MethodName.Rotate, new Vector3(1f, 0f, 0f), 1.571f);
|
||
|
||
|
||
|
||
For methods that are deferred from the same thread, the order of execution at idle time is identical to the order in which ``call_deferred`` was called.
|
||
|
||
See also :ref:`Callable.call_deferred()<class_Callable_method_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 :ref:`StringName<class_StringName>` on each call.
|
||
|
||
\ **Note:** If you're looking to delay the function call by a frame, refer to the :ref:`SceneTree.process_frame<class_SceneTree_signal_process_frame>` and :ref:`SceneTree.physics_frame<class_SceneTree_signal_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)
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_callv:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **callv**\ (\ method\: :ref:`StringName<class_StringName>`, arg_array\: :ref:`Array<class_Array>`\ ) :ref:`🔗<class_Object_method_callv>`
|
||
|
||
Вызывает ``method`` на объекте и возвращает результат. В отличие от :ref:`call()<class_Object_method_call>`, этот метод ожидает, что все параметры будут содержаться внутри ``arg_array``.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
var node = Node3D.new()
|
||
node.callv("rotate", [Vector3(1.0, 0.0, 0.0), 1.571])
|
||
|
||
.. code-tab:: csharp
|
||
|
||
var node = new Node3D();
|
||
node.Callv(Node3D.MethodName.Rotate, [new Vector3(1f, 0f, 0f), 1.571f]);
|
||
|
||
|
||
|
||
\ **Примечание:** В C# ``method`` должен быть в snake_case при ссылке на встроенные методы Godot. Предпочитайте использовать имена, представленные в классе ``MethodName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_can_translate_messages:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **can_translate_messages**\ (\ ) |const| :ref:`🔗<class_Object_method_can_translate_messages>`
|
||
|
||
Возвращает ``true``, если объекту разрешено переводить сообщения с помощью :ref:`tr()<class_Object_method_tr>` и :ref:`tr_n()<class_Object_method_tr_n>`. См. также :ref:`set_message_translation()<class_Object_method_set_message_translation>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_cancel_free:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **cancel_free**\ (\ ) :ref:`🔗<class_Object_method_cancel_free>`
|
||
|
||
Если этот метод вызывается во время :ref:`NOTIFICATION_PREDELETE<class_Object_constant_NOTIFICATION_PREDELETE>`, этот объект отклонит освобождение и останется выделенным. Это в основном внутренняя функция, используемая для обработки ошибок, чтобы пользователь не освобождал объекты, когда они не предназначены для этого.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_connect:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **connect**\ (\ signal\: :ref:`StringName<class_StringName>`, callable\: :ref:`Callable<class_Callable>`, flags\: :ref:`int<class_int>` = 0\ ) :ref:`🔗<class_Object_method_connect>`
|
||
|
||
Connects a ``signal`` by name to a ``callable``. Optional ``flags`` can be also added to configure the connection's behavior (see :ref:`ConnectFlags<enum_Object_ConnectFlags>` constants).
|
||
|
||
A signal can only be connected once to the same :ref:`Callable<class_Callable>`. If the signal is already connected, this method returns :ref:`@GlobalScope.ERR_INVALID_PARAMETER<class_@GlobalScope_constant_ERR_INVALID_PARAMETER>` and generates an error, unless the signal is connected with :ref:`CONNECT_REFERENCE_COUNTED<class_Object_constant_CONNECT_REFERENCE_COUNTED>`. To prevent this, use :ref:`is_connected()<class_Object_method_is_connected>` first to check for existing connections.
|
||
|
||
\ **Note:** If the ``callable``'s object is freed, the connection will be lost.
|
||
|
||
\ **Note:** In GDScript, it is generally recommended to connect signals with :ref:`Signal.connect()<class_Signal_method_connect>` instead.
|
||
|
||
\ **Note:** This method, and all other signal-related methods, are thread-safe.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_disconnect:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **disconnect**\ (\ signal\: :ref:`StringName<class_StringName>`, callable\: :ref:`Callable<class_Callable>`\ ) :ref:`🔗<class_Object_method_disconnect>`
|
||
|
||
Отключает ``signal`` по имени от заданного ``callable``. Если соединение не существует, генерирует ошибку. Используйте :ref:`is_connected()<class_Object_method_is_connected>`, чтобы убедиться, что соединение существует.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_emit_signal:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Error<enum_@GlobalScope_Error>` **emit_signal**\ (\ signal\: :ref:`StringName<class_StringName>`, ...\ ) |vararg| :ref:`🔗<class_Object_method_emit_signal>`
|
||
|
||
Выдает заданный ``signal`` по имени. Сигнал должен существовать, поэтому он должен быть встроенным сигналом этого класса или одного из его унаследованных классов, или определяемым пользователем сигналом (см. :ref:`add_user_signal()<class_Object_method_add_user_signal>`). Этот метод поддерживает переменное количество аргументов, поэтому параметры можно передавать в виде списка, разделенного запятыми.
|
||
|
||
Возвращает :ref:`@GlobalScope.ERR_UNAVAILABLE<class_@GlobalScope_constant_ERR_UNAVAILABLE>`, если ``signal`` не существует или параметры недопустимы.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
emit_signal("hit", "sword", 100)
|
||
emit_signal("game_over")
|
||
|
||
.. code-tab:: csharp
|
||
|
||
EmitSignal(SignalName.Hit, "sword", 100);
|
||
EmitSignal(SignalName.GameOver);
|
||
|
||
|
||
|
||
\ **Примечание:** В C# ``signal`` должен быть в snake_case при ссылке на встроенные сигналы Godot. Предпочитайте использовать имена, представленные в классе ``SignalName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_free:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **free**\ (\ ) :ref:`🔗<class_Object_method_free>`
|
||
|
||
Удаляет объект из памяти. Существующие ранее ссылки на объект становятся недействительными, и любая попытка доступа к ним приведет к ошибке выполнения. Проверка ссылок с помощью :ref:`@GlobalScope.is_instance_valid()<class_@GlobalScope_method_is_instance_valid>` вернет ``false``. Это эквивалентно функции ``memdelete`` в GDExtension C++.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **get**\ (\ property\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_get>`
|
||
|
||
Возвращает значение :ref:`Variant<class_Variant>` указанного ``property``. Если ``property`` не существует, этот метод возвращает ``null``.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
var node = Node2D.new()
|
||
node.rotation = 1.5
|
||
var a = node.get("rotation") # а равно 1,5
|
||
|
||
.. code-tab:: csharp
|
||
|
||
var node = new Node2D();
|
||
node.Rotation = 1.5f;
|
||
var a = node.Get(Node2D.PropertyName.Rotation); // а равно 1,5
|
||
|
||
|
||
|
||
\ **Примечание:** В C# ``property`` должно быть в snake_case при ссылке на встроенные свойства Godot. Предпочитайте использовать имена, представленные в классе ``PropertyName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_class:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **get_class**\ (\ ) |const| :ref:`🔗<class_Object_method_get_class>`
|
||
|
||
Возвращает встроенное имя класса объекта в виде :ref:`String<class_String>`. См. также :ref:`is_class()<class_Object_method_is_class>`.
|
||
|
||
\ **Примечание:** Этот метод игнорирует объявления ``class_name``. Если скрипт этого объекта определил ``class_name``, вместо этого возвращается базовое встроенное имя класса.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_incoming_connections:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] **get_incoming_connections**\ (\ ) |const| :ref:`🔗<class_Object_method_get_incoming_connections>`
|
||
|
||
Возвращает :ref:`Array<class_Array>` соединений сигналов, полученных этим объектом. Каждое соединение представлено как :ref:`Dictionary<class_Dictionary>`, который содержит три записи:
|
||
|
||
- ``signal`` — ссылка на :ref:`Signal<class_Signal>`;
|
||
|
||
- ``callable`` — ссылка на :ref:`Callable<class_Callable>`;
|
||
|
||
- ``flags`` — комбинация :ref:`ConnectFlags<enum_Object_ConnectFlags>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_indexed:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **get_indexed**\ (\ property_path\: :ref:`NodePath<class_NodePath>`\ ) |const| :ref:`🔗<class_Object_method_get_indexed>`
|
||
|
||
Получает свойство объекта, индексированное заданным ``property_path``. Путь должен быть :ref:`NodePath<class_NodePath>` относительно текущего объекта и может использовать символ двоеточия (``:``) для доступа к вложенным свойствам.
|
||
|
||
\ **Примеры:** ``"position:x"`` или ``"material:next_pass:blend_mode"``.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
var node = Node2D.new()
|
||
node.position = Vector2(5, -10)
|
||
var a = node.get_indexed("position") # а — это Vector2(5, -10)
|
||
var b = node.get_indexed("position:y") # b это -10
|
||
|
||
.. code-tab:: csharp
|
||
|
||
var node = new Node2D();
|
||
node.Position = new Vector2(5, -10);
|
||
var a = node.GetIndexed("position"); // а — это Vector2(5, -10)
|
||
var b = node.GetIndexed("position:y"); // b это -10
|
||
|
||
|
||
|
||
\ **Примечание:** В C# ``property_path`` должен быть в snake_case при ссылке на встроенные свойства Godot. Предпочитайте использовать имена, представленные в классе ``PropertyName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
\ **Примечание:** Этот метод не поддерживает фактические пути к узлам в :ref:`SceneTree<class_SceneTree>`, только пути подсвойств. В контексте узлов используйте вместо этого :ref:`Node.get_node_and_resource()<class_Node_method_get_node_and_resource>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_instance_id:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_instance_id**\ (\ ) |const| :ref:`🔗<class_Object_method_get_instance_id>`
|
||
|
||
Возвращает уникальный идентификатор экземпляра объекта. Этот идентификатор можно сохранить в :ref:`EncodedObjectAsID<class_EncodedObjectAsID>` и использовать для извлечения этого экземпляра объекта с помощью :ref:`@GlobalScope.instance_from_id()<class_@GlobalScope_method_instance_from_id>`.
|
||
|
||
\ **Примечание:** Этот идентификатор полезен только во время текущего сеанса. Он не будет соответствовать похожему объекту, если идентификатор будет отправлен по сети или загружен из файла позднее.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_meta:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **get_meta**\ (\ name\: :ref:`StringName<class_StringName>`, default\: :ref:`Variant<class_Variant>` = null\ ) |const| :ref:`🔗<class_Object_method_get_meta>`
|
||
|
||
Возвращает значение метаданных объекта для заданной записи ``name``. Если запись не существует, возвращает ``default``. Если ``default`` равен ``null``, также генерируется ошибка.
|
||
|
||
\ **Примечание:** Имя метаданных должно быть допустимым идентификатором согласно методу :ref:`StringName.is_valid_identifier()<class_StringName_method_is_valid_identifier>`.
|
||
|
||
\ **Примечание:** Метаданные, имя которых начинается с подчеркивания (``_``), считаются доступными только для редактора. Метаданные, доступные только для редактора, не отображаются в Инспекторе и не должны редактироваться, хотя их все равно можно найти с помощью этого метода.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_meta_list:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Array<class_Array>`\[:ref:`StringName<class_StringName>`\] **get_meta_list**\ (\ ) |const| :ref:`🔗<class_Object_method_get_meta_list>`
|
||
|
||
Возвращает имена записей метаданных объекта в виде :ref:`Array<class_Array>` из :ref:`StringName<class_StringName>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_method_argument_count:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`int<class_int>` **get_method_argument_count**\ (\ method\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_get_method_argument_count>`
|
||
|
||
Возвращает количество аргументов указанного ``method`` по имени.
|
||
|
||
\ **Примечание:** В C# ``method`` должен быть в snake_case при ссылке на встроенные методы Godot. Предпочитайте использовать имена, представленные в классе ``MethodName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_method_list:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] **get_method_list**\ (\ ) |const| :ref:`🔗<class_Object_method_get_method_list>`
|
||
|
||
Возвращает методы этого объекта и их сигнатуры как :ref:`Array<class_Array>` словарей. Каждый :ref:`Dictionary<class_Dictionary>` содержит следующие записи:
|
||
|
||
- ``name`` — имя метода, как :ref:`String<class_String>`;
|
||
|
||
- ``args`` — :ref:`Array<class_Array>` словарей, представляющих аргументы;
|
||
|
||
- ``default_args`` — аргументы по умолчанию как :ref:`Array<class_Array>` вариантов;
|
||
|
||
- ``flags`` — комбинация :ref:`MethodFlags<enum_@GlobalScope_MethodFlags>`;
|
||
|
||
- ``id`` — внутренний идентификатор метода :ref:`int<class_int>`;
|
||
|
||
- ``return`` — возвращаемое значение, как :ref:`Dictionary<class_Dictionary>`;
|
||
|
||
\ **Примечание:** Словари ``args`` и ``return`` форматируются идентично результатам :ref:`get_property_list()<class_Object_method_get_property_list>`, хотя используются не все записи.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_property_list:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] **get_property_list**\ (\ ) |const| :ref:`🔗<class_Object_method_get_property_list>`
|
||
|
||
Возвращает список свойств объекта как :ref:`Array<class_Array>` словарей. Каждый :ref:`Dictionary<class_Dictionary>` содержит следующие записи:
|
||
|
||
- ``name`` — имя свойства, как :ref:`String<class_String>`;
|
||
|
||
- ``class_name`` — пустой :ref:`StringName<class_StringName>`, если свойство не является :ref:`@GlobalScope.TYPE_OBJECT<class_@GlobalScope_constant_TYPE_OBJECT>` и не наследуется от класса;
|
||
|
||
- ``type`` — тип свойства, как :ref:`int<class_int>` (см. :ref:`Variant.Type<enum_@GlobalScope_Variant.Type>`);
|
||
|
||
- ``hint`` — *как* свойство должно редактироваться (см. :ref:`PropertyHint<enum_@GlobalScope_PropertyHint>`);
|
||
|
||
- ``hint_string`` зависит от подсказки (см. :ref:`PropertyHint<enum_@GlobalScope_PropertyHint>`);
|
||
|
||
- ``usage`` — комбинация :ref:`PropertyUsageFlags<enum_@GlobalScope_PropertyUsageFlags>`.
|
||
|
||
\ **Примечание:** В GDScript все члены класса рассматриваются как свойства. В C# и GDExtension может потребоваться явно пометить члены класса как свойства Godot с помощью декораторов или атрибутов.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_script:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **get_script**\ (\ ) |const| :ref:`🔗<class_Object_method_get_script>`
|
||
|
||
Возвращает экземпляр :ref:`Script<class_Script>` объекта или ``null``, если скрипт не прикреплен.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_signal_connection_list:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] **get_signal_connection_list**\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_get_signal_connection_list>`
|
||
|
||
Возвращает :ref:`Array<class_Array>` соединений для заданного имени ``signal``. Каждое соединение представлено как :ref:`Dictionary<class_Dictionary>`, содержащий три записи:
|
||
|
||
- ``signal`` — ссылка на :ref:`Signal<class_Signal>`;
|
||
|
||
- ``callable`` — ссылка на подключенный :ref:`Callable<class_Callable>`;
|
||
|
||
- ``flags`` — комбинация :ref:`ConnectFlags<enum_Object_ConnectFlags>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_signal_list:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Array<class_Array>`\[:ref:`Dictionary<class_Dictionary>`\] **get_signal_list**\ (\ ) |const| :ref:`🔗<class_Object_method_get_signal_list>`
|
||
|
||
Returns the list of existing signals as an :ref:`Array<class_Array>` of dictionaries.
|
||
|
||
\ **Note:** Due to the implementation, each :ref:`Dictionary<class_Dictionary>` is formatted very similarly to the returned values of :ref:`get_method_list()<class_Object_method_get_method_list>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_get_translation_domain:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`StringName<class_StringName>` **get_translation_domain**\ (\ ) |const| :ref:`🔗<class_Object_method_get_translation_domain>`
|
||
|
||
Возвращает имя домена перевода, используемого :ref:`tr()<class_Object_method_tr>` и :ref:`tr_n()<class_Object_method_tr_n>`. См. также :ref:`TranslationServer<class_TranslationServer>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_has_connections:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **has_connections**\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_has_connections>`
|
||
|
||
Возвращает ``true``, если существует какое-либо соединение по заданному имени ``signal``.
|
||
|
||
\ **Примечание:** В C# ``signal`` должен быть в snake_case при ссылке на встроенные методы Godot. Предпочитайте использовать имена, представленные в классе ``SignalName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_has_meta:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **has_meta**\ (\ name\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_has_meta>`
|
||
|
||
Возвращает ``true``, если найдена запись метаданных с указанным ``name``. См. также :ref:`get_meta()<class_Object_method_get_meta>`, :ref:`set_meta()<class_Object_method_set_meta>` и :ref:`remove_meta()<class_Object_method_remove_meta>`.
|
||
|
||
\ **Примечание:** Имя метаданных должно быть допустимым идентификатором согласно методу :ref:`StringName.is_valid_identifier()<class_StringName_method_is_valid_identifier>`.
|
||
|
||
\ **Примечание:** Метаданные, имя которых начинается с подчеркивания (``_``), считаются доступными только для редактора. Доступные только для редактора метаданные не отображаются в Инспекторе и не должны редактироваться, хотя их все равно можно найти с помощью этого метода.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_has_method:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **has_method**\ (\ method\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_has_method>`
|
||
|
||
Возвращает ``true``, если заданное имя ``method`` существует в объекте.
|
||
|
||
\ **Примечание:** В C# ``method`` должно быть в snake_case при ссылке на встроенные методы Godot. Предпочитайте использовать имена, представленные в классе ``MethodName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_has_signal:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **has_signal**\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_has_signal>`
|
||
|
||
Возвращает ``true``, если заданное имя ``signal`` существует в объекте.
|
||
|
||
\ **Примечание:** В C# ``signal`` должен быть в snake_case при ссылке на встроенные сигналы Godot. Предпочитайте использовать имена, представленные в классе ``SignalName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_has_user_signal:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **has_user_signal**\ (\ signal\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_has_user_signal>`
|
||
|
||
Возвращает ``true``, если заданное пользователем имя ``signal`` существует. Включаются только сигналы, добавленные с помощью :ref:`add_user_signal()<class_Object_method_add_user_signal>`. См. также :ref:`remove_user_signal()<class_Object_method_remove_user_signal>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_is_blocking_signals:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **is_blocking_signals**\ (\ ) |const| :ref:`🔗<class_Object_method_is_blocking_signals>`
|
||
|
||
Возвращает ``true``, если объект блокирует передачу своих сигналов. См. :ref:`set_block_signals()<class_Object_method_set_block_signals>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_is_class:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **is_class**\ (\ class\: :ref:`String<class_String>`\ ) |const| :ref:`🔗<class_Object_method_is_class>`
|
||
|
||
Возвращает ``true``, если объект наследуется от указанного ``class``. См. также :ref:`get_class()<class_Object_method_get_class>`.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
var sprite2d = Sprite2D.new()
|
||
sprite2d.is_class("Sprite2D") # Возвращает true
|
||
sprite2d.is_class("Node") # Возвращает true
|
||
sprite2d.is_class("Node3D") # Возвращает false
|
||
|
||
.. code-tab:: csharp
|
||
|
||
var sprite2D = new Sprite2D();
|
||
sprite2D.IsClass("Sprite2D"); // Возвращает true
|
||
sprite2D.IsClass("Node"); // Возвращает true
|
||
sprite2D.IsClass("Node3D"); // Возвращает false
|
||
|
||
|
||
|
||
\ **Примечание:** Этот метод игнорирует объявления ``class_name`` в скрипте объекта.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_is_connected:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **is_connected**\ (\ signal\: :ref:`StringName<class_StringName>`, callable\: :ref:`Callable<class_Callable>`\ ) |const| :ref:`🔗<class_Object_method_is_connected>`
|
||
|
||
Возвращает ``true``, если существует связь между заданным именем ``signal`` и ``callable``.
|
||
|
||
\ **Примечание:** В C# ``signal`` должен быть в snake_case при ссылке на встроенные сигналы Godot. Предпочитайте использовать имена, представленные в классе ``SignalName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_is_queued_for_deletion:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **is_queued_for_deletion**\ (\ ) |const| :ref:`🔗<class_Object_method_is_queued_for_deletion>`
|
||
|
||
Возвращает ``true``, если для объекта был вызван метод :ref:`Node.queue_free()<class_Node_method_queue_free>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_notification:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **notification**\ (\ what\: :ref:`int<class_int>`, reversed\: :ref:`bool<class_bool>` = false\ ) :ref:`🔗<class_Object_method_notification>`
|
||
|
||
Отправляет заданное уведомление ``what`` всем классам, унаследованным объектом, вызывая вызовы :ref:`_notification()<class_Object_private_method__notification>`, начиная с наивысшего предка (класса **Object**) и спускаясь к скрипту объекта.
|
||
|
||
Если ``reversed`` равен ``true``, порядок вызовов меняется на обратный.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
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.
|
||
|
||
.. code-tab:: csharp
|
||
|
||
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.
|
||
|
||
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_notify_property_list_changed:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **notify_property_list_changed**\ (\ ) :ref:`🔗<class_Object_method_notify_property_list_changed>`
|
||
|
||
Выдает сигнал :ref:`property_list_changed<class_Object_signal_property_list_changed>`. В основном он используется для обновления редактора, чтобы плагины Inspector и editor были обновлены должным образом.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_property_can_revert:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`bool<class_bool>` **property_can_revert**\ (\ property\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_property_can_revert>`
|
||
|
||
Возвращает ``true``, если заданное ``property`` имеет пользовательское значение по умолчанию. Используйте :ref:`property_get_revert()<class_Object_method_property_get_revert>`, чтобы получить значение по умолчанию для ``property``.
|
||
|
||
\ **Примечание:** Этот метод используется панелью инспектора для отображения значка возврата. Объект должен реализовать :ref:`_property_can_revert()<class_Object_private_method__property_can_revert>` для настройки значения по умолчанию. Если :ref:`_property_can_revert()<class_Object_private_method__property_can_revert>` не реализован, этот метод возвращает ``false``.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_property_get_revert:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`Variant<class_Variant>` **property_get_revert**\ (\ property\: :ref:`StringName<class_StringName>`\ ) |const| :ref:`🔗<class_Object_method_property_get_revert>`
|
||
|
||
Возвращает пользовательское значение по умолчанию для указанного ``property``. Используйте :ref:`property_can_revert()<class_Object_method_property_can_revert>`, чтобы проверить, имеет ли ``property`` пользовательское значение по умолчанию.
|
||
|
||
\ **Примечание:** Этот метод используется панелью инспектора для отображения значка возврата. Объект должен реализовать :ref:`_property_get_revert()<class_Object_private_method__property_get_revert>` для настройки значения по умолчанию. Если :ref:`_property_get_revert()<class_Object_private_method__property_get_revert>` не реализован, этот метод возвращает ``null``.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_remove_meta:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **remove_meta**\ (\ name\: :ref:`StringName<class_StringName>`\ ) :ref:`🔗<class_Object_method_remove_meta>`
|
||
|
||
Удаляет указанную запись ``name`` из метаданных объекта. См. также :ref:`has_meta()<class_Object_method_has_meta>`, :ref:`get_meta()<class_Object_method_get_meta>` и :ref:`set_meta()<class_Object_method_set_meta>`.
|
||
|
||
\ **Примечание:** Имя метаданных должно быть допустимым идентификатором согласно методу :ref:`StringName.is_valid_identifier()<class_StringName_method_is_valid_identifier>`.
|
||
|
||
\ **Примечание:** Метаданные, имя которых начинается с подчеркивания (``_``), считаются доступными только для редактора. Доступные только для редактора метаданные не отображаются в Инспекторе и не должны редактироваться, хотя их все равно можно найти с помощью этого метода.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_remove_user_signal:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **remove_user_signal**\ (\ signal\: :ref:`StringName<class_StringName>`\ ) :ref:`🔗<class_Object_method_remove_user_signal>`
|
||
|
||
Удаляет указанный пользовательский сигнал ``signal`` из объекта. См. также :ref:`add_user_signal()<class_Object_method_add_user_signal>` и :ref:`has_user_signal()<class_Object_method_has_user_signal>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_set:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **set**\ (\ property\: :ref:`StringName<class_StringName>`, value\: :ref:`Variant<class_Variant>`\ ) :ref:`🔗<class_Object_method_set>`
|
||
|
||
Назначает ``value`` заданному ``property``. Если свойство не существует или тип заданного ``value`` не совпадает, ничего не происходит.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
var node = Node2D.new()
|
||
node.set("global_scale", Vector2(8, 2.5))
|
||
print(node.global_scale) # Prints (8.0, 2.5)
|
||
|
||
.. code-tab:: csharp
|
||
|
||
var node = new Node2D();
|
||
node.Set(Node2D.PropertyName.GlobalScale, new Vector2(8, 2.5f));
|
||
GD.Print(node.GlobalScale); // Prints (8, 2.5)
|
||
|
||
|
||
|
||
\ **Примечание:** В C# ``property`` должно быть в snake_case при ссылке на встроенные свойства Godot. Предпочитайте использовать имена, представленные в классе ``PropertyName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_set_block_signals:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **set_block_signals**\ (\ enable\: :ref:`bool<class_bool>`\ ) :ref:`🔗<class_Object_method_set_block_signals>`
|
||
|
||
Если установлено значение ``true``, объект становится неспособным испускать сигналы. Таким образом, :ref:`emit_signal()<class_Object_method_emit_signal>` и сигнальные соединения не будут работать, пока не будет установлено значение ``false``.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_set_deferred:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **set_deferred**\ (\ property\: :ref:`StringName<class_StringName>`, value\: :ref:`Variant<class_Variant>`\ ) :ref:`🔗<class_Object_method_set_deferred>`
|
||
|
||
Назначает ``value`` заданному ``property`` в конце текущего кадра. Это эквивалентно вызову :ref:`set()<class_Object_method_set>` через :ref:`call_deferred()<class_Object_method_call_deferred>`.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
var node = Node2D.new()
|
||
add_child(node)
|
||
|
||
node.rotation = 1.5
|
||
node.set_deferred("rotation", 3.0)
|
||
print(node.rotation) # Prints 1.5
|
||
|
||
await get_tree().process_frame
|
||
print(node.rotation) # Prints 3.0
|
||
|
||
.. code-tab:: csharp
|
||
|
||
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
|
||
|
||
|
||
|
||
\ **Примечание:** В C# ``property`` должно быть в snake_case при ссылке на встроенные свойства Godot. Предпочитайте использовать имена, представленные в классе ``PropertyName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_set_indexed:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **set_indexed**\ (\ property_path\: :ref:`NodePath<class_NodePath>`, value\: :ref:`Variant<class_Variant>`\ ) :ref:`🔗<class_Object_method_set_indexed>`
|
||
|
||
Назначает новое ``value`` свойству, идентифицированному ``property_path``. Путь должен быть :ref:`NodePath<class_NodePath>` относительно этого объекта и может использовать символ двоеточия (``:``) для доступа к вложенным свойствам.
|
||
|
||
|
||
.. tabs::
|
||
|
||
.. code-tab:: gdscript
|
||
|
||
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)
|
||
|
||
.. code-tab:: csharp
|
||
|
||
var node = new Node2D();
|
||
node.SetIndexed("position", new Vector2(42, 0));
|
||
node.SetIndexed("position:y", -10);
|
||
GD.Print(node.Position); // Prints (42, -10)
|
||
|
||
|
||
|
||
\ **Примечание:** В C# ``property_path`` должен быть в snake_case при ссылке на встроенные свойства Godot. Предпочитайте использовать имена, представленные в классе ``PropertyName``, чтобы избежать выделения нового :ref:`StringName<class_StringName>` при каждом вызове.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_set_message_translation:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **set_message_translation**\ (\ enable\: :ref:`bool<class_bool>`\ ) :ref:`🔗<class_Object_method_set_message_translation>`
|
||
|
||
Если установлено значение ``true``, позволяет объекту переводить сообщения с помощью :ref:`tr()<class_Object_method_tr>` и :ref:`tr_n()<class_Object_method_tr_n>`. Включено по умолчанию. См. также :ref:`can_translate_messages()<class_Object_method_can_translate_messages>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_set_meta:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **set_meta**\ (\ name\: :ref:`StringName<class_StringName>`, value\: :ref:`Variant<class_Variant>`\ ) :ref:`🔗<class_Object_method_set_meta>`
|
||
|
||
Добавляет или изменяет запись ``name`` внутри метаданных объекта. Метаданные ``value`` могут быть любым :ref:`Variant<class_Variant>`, хотя некоторые типы не могут быть сериализованы правильно.
|
||
|
||
Если ``value`` равно ``null``, запись удаляется. Это эквивалентно использованию :ref:`remove_meta()<class_Object_method_remove_meta>`. См. также :ref:`has_meta()<class_Object_method_has_meta>` и :ref:`get_meta()<class_Object_method_get_meta>`.
|
||
|
||
\ **Примечание:** Имя метаданных должно быть допустимым идентификатором согласно методу :ref:`StringName.is_valid_identifier()<class_StringName_method_is_valid_identifier>`.
|
||
|
||
\ **Примечание:** Метаданные, имя которых начинается с подчеркивания (``_``), считаются доступными только для редактора. Метаданные, доступные только для редактора, не отображаются в Инспекторе и не должны редактироваться, хотя их все равно можно найти с помощью этого метода.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_set_script:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **set_script**\ (\ script\: :ref:`Variant<class_Variant>`\ ) :ref:`🔗<class_Object_method_set_script>`
|
||
|
||
Прикрепляет ``script`` к объекту и создает его экземпляр. В результате вызывается :ref:`_init()<class_Object_private_method__init>` скрипта. :ref:`Script<class_Script>` используется для расширения функциональности объекта.
|
||
|
||
Если скрипт уже существует, его экземпляр отсоединяется, а его значения свойств и состояние теряются. Встроенные значения свойств по-прежнему сохраняются.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_set_translation_domain:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
|void| **set_translation_domain**\ (\ domain\: :ref:`StringName<class_StringName>`\ ) :ref:`🔗<class_Object_method_set_translation_domain>`
|
||
|
||
Устанавливает имя домена перевода, используемого :ref:`tr()<class_Object_method_tr>` и :ref:`tr_n()<class_Object_method_tr_n>`. См. также :ref:`TranslationServer<class_TranslationServer>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_to_string:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **to_string**\ (\ ) :ref:`🔗<class_Object_method_to_string>`
|
||
|
||
Возвращает :ref:`String<class_String>`, представляющую объект. По умолчанию ``"<ClassName#RID>"``. Переопределите :ref:`_to_string()<class_Object_private_method__to_string>`, чтобы настроить строковое представление объекта.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_tr:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **tr**\ (\ message\: :ref:`StringName<class_StringName>`, context\: :ref:`StringName<class_StringName>` = &""\ ) |const| :ref:`🔗<class_Object_method_tr>`
|
||
|
||
Переводит ``message``, используя каталоги перевода, настроенные в настройках проекта. Для помощи с переводом можно указать дополнительный ``context``. Обратите внимание, что большинство узлов :ref:`Control<class_Control>` автоматически переводят свои строки, поэтому этот метод в основном полезен для форматированных строк или нарисованного текста.
|
||
|
||
Если :ref:`can_translate_messages()<class_Object_method_can_translate_messages>` равен ``false`` или перевод недоступен, этот метод возвращает ``message`` без изменений. См. :ref:`set_message_translation()<class_Object_method_set_message_translation>`.
|
||
|
||
Подробные примеры см. в :doc:`Интернационализация игр <../tutorials/i18n/internationalizing_games>`.
|
||
|
||
\ **Примечание:** Этот метод нельзя использовать без экземпляра **Object**, так как для него требуется метод :ref:`can_translate_messages()<class_Object_method_can_translate_messages>`. Чтобы перевести строки в статическом контексте, используйте :ref:`TranslationServer.translate()<class_TranslationServer_method_translate>`.
|
||
|
||
.. rst-class:: classref-item-separator
|
||
|
||
----
|
||
|
||
.. _class_Object_method_tr_n:
|
||
|
||
.. rst-class:: classref-method
|
||
|
||
:ref:`String<class_String>` **tr_n**\ (\ message\: :ref:`StringName<class_StringName>`, plural_message\: :ref:`StringName<class_StringName>`, n\: :ref:`int<class_int>`, context\: :ref:`StringName<class_StringName>` = &""\ ) |const| :ref:`🔗<class_Object_method_tr_n>`
|
||
|
||
Переводит ``message`` или ``plural_message``, используя каталоги перевода, настроенные в настройках проекта. Для помощи с переводом можно указать дополнительный ``context``.
|
||
|
||
Если :ref:`can_translate_messages()<class_Object_method_can_translate_messages>` равен ``false`` или перевод недоступен, этот метод возвращает ``message`` или ``plural_message`` без изменений. См. :ref:`set_message_translation()<class_Object_method_set_message_translation>`.
|
||
|
||
\ ``n`` — это номер или количество темы сообщения. Он используется системой перевода для получения правильной формы множественного числа для текущего языка.
|
||
|
||
Подробные примеры см. в :doc:`Локализация с использованием gettext <../tutorials/i18n/localization_using_gettext>`.
|
||
|
||
\ **Примечание:** Отрицательные и :ref:`float<class_float>` числа могут неправильно применяться к некоторым исчисляемым темам. Рекомендуется обрабатывать эти случаи с помощью :ref:`tr()<class_Object_method_tr>`.
|
||
|
||
\ **Примечание:** Этот метод нельзя использовать без экземпляра **Object**, так как он требует метод :ref:`can_translate_messages()<class_Object_method_can_translate_messages>`. Для перевода строк в статическом контексте используйте :ref:`TranslationServer.translate_plural()<class_TranslationServer_method_translate_plural>`.
|
||
|
||
.. |virtual| replace:: :abbr:`virtual (Этот метод обычно должен быть переопределен пользователем, чтобы иметь какой-либо эффект.)`
|
||
.. |required| replace:: :abbr:`required (This method is required to be overridden when extending its base class.)`
|
||
.. |const| replace:: :abbr:`const (Этот метод не имеет побочных эффектов. Он не изменяет ни одну из переменных-членов экземпляра.)`
|
||
.. |vararg| replace:: :abbr:`vararg (Этот метод принимает любое количество аргументов после описанных здесь.)`
|
||
.. |constructor| replace:: :abbr:`constructor (Этот метод используется для создания типа.)`
|
||
.. |static| replace:: :abbr:`static (Этот метод не нуждается в вызове экземпляра, поэтому его можно вызвать напрямую, используя имя класса.)`
|
||
.. |operator| replace:: :abbr:`operator (Этот метод описывает допустимый оператор для использования с этим типом в качестве левого операнда.)`
|
||
.. |bitfield| replace:: :abbr:`BitField (Это значение является целым числом, составленным как битовая маска следующих флагов.)`
|
||
.. |void| replace:: :abbr:`void (Нет возвращаемого значения.)`
|