object_class.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. .. _doc_object_class:
  2. Object class
  3. ============
  4. .. seealso::
  5. This page describes the C++ implementation of objects in Godot.
  6. Looking for the Object class reference? :ref:`Have a look here. <class_Object>`
  7. General definition
  8. ------------------
  9. :ref:`Object <class_object>` is the base class for almost everything. Most classes in Godot
  10. inherit directly or indirectly from it. Declaring them is a matter of using a single
  11. macro like this:
  12. .. code-block:: cpp
  13. class CustomObject : public Object {
  14. GDCLASS(CustomObject, Object); // This is required to inherit from Object.
  15. };
  16. Objects come with a lot of built-in functionality, like reflection and editable properties:
  17. .. code-block:: cpp
  18. CustomObject *obj = memnew(CustomObject);
  19. print_line("Object class: ", obj->get_class()); // print object class
  20. OtherClass *obj2 = Object::cast_to<OtherClass>(obj); // Converting between classes, similar to dynamic_cast
  21. References:
  22. ~~~~~~~~~~~
  23. - `core/object/object.h <https://github.com/godotengine/godot/blob/master/core/object/object.h>`__
  24. Registering Object classes
  25. --------------------------
  26. Most ``Object`` subclasses are registered by calling ``GDREGISTER_CLASS``.
  27. .. code-block:: cpp
  28. GDREGISTER_CLASS(MyCustomClass)
  29. This will register it as a named, public class in the ``ClassDB``, which will allow the class to be instantiated by
  30. scripts, code, or by deserialization. Note that classes registered as ``GDREGISTER_CLASS`` should expect to be
  31. instantiated or freed automatically, for example by the editor or the documentation system.
  32. Besides ``GDREGISTER_CLASS``, there are a few other modes of privateness:
  33. .. code-block:: cpp
  34. // Registers the class publicly, but prevents automatic instantiation through ClassDB.
  35. GDREGISTER_VIRTUAL_CLASS(MyCustomClass);
  36. // Registers the class publicly, but prevents all instantiation through ClassDB.
  37. GDREGISTER_ABSTRACT_CLASS(MyCustomClass);
  38. // Registers the class in ClassDB, but marks it as private,
  39. // such that it is not visible to scripts or extensions.
  40. // This is the same as not registering the class explicitly at all
  41. // - in this case, the class is registered as internal automatically
  42. // when it is first constructed.
  43. GDREGISTER_INTERNAL_CLASS(MyCustomClass);
  44. // Registers the class such that it is only available at runtime (but not in the editor).
  45. GDREGISTER_RUNTIME_CLASS(MyCustomClass);
  46. It is also possible to use ``GDSOFTCLASS(MyCustomClass, SuperClass)`` instead of ``GDCLASS(MyCustomClass, SuperClass)``.
  47. Classes defined this way are not registered in the ``ClassDB`` at all. This is sometimes used for platform-specific
  48. subclasses.
  49. Registering bindings
  50. ~~~~~~~~~~~~~~~~~~~~
  51. Object-derived classes can override the static function
  52. ``static void _bind_methods()``. When the class is registered, this
  53. static function is called to register all the object methods,
  54. properties, constants, etc. It's only called once.
  55. Inside ``_bind_methods``, there are a couple of things that can be done.
  56. Registering functions is one:
  57. .. code-block:: cpp
  58. ClassDB::bind_method(D_METHOD("methodname", "arg1name", "arg2name", "arg3name"), &MyCustomType::method);
  59. Default values for arguments can be passed as parameters at the end:
  60. .. code-block:: cpp
  61. ClassDB::bind_method(D_METHOD("methodname", "arg1name", "arg2name", "arg3name"), &MyCustomType::method, DEFVAL(-1), DEFVAL(-2)); // Default values for arg2name (-1) and arg3name (-2).
  62. Default values must be provided in the same order as they are declared,
  63. skipping required arguments and then providing default values for the optional ones.
  64. This matches the syntax for declaring methods in C++.
  65. ``D_METHOD`` is a macro that converts "methodname" to a StringName for more
  66. efficiency. Argument names are used for introspection, but when
  67. compiling on release, the macro ignores them, so the strings are unused
  68. and optimized away.
  69. Check ``_bind_methods`` of Control or Object for more examples.
  70. If just adding modules and functionality that is not expected to be
  71. documented as thoroughly, the ``D_METHOD()`` macro can safely be ignored and a
  72. string passing the name can be passed for brevity.
  73. References:
  74. ^^^^^^^^^^^
  75. - `core/object/class_db.h <https://github.com/godotengine/godot/blob/master/core/object/class_db.h>`__
  76. Constants
  77. ~~~~~~~~~
  78. Classes often have enums such as:
  79. .. code-block:: cpp
  80. enum SomeMode {
  81. MODE_FIRST,
  82. MODE_SECOND
  83. };
  84. For these to work when binding to methods, the enum must be declared
  85. convertible to int. A macro is provided to help with this:
  86. .. code-block:: cpp
  87. VARIANT_ENUM_CAST(MyClass::SomeMode); // now functions that take SomeMode can be bound.
  88. The constants can also be bound inside ``_bind_methods``, by using:
  89. .. code-block:: cpp
  90. BIND_CONSTANT(MODE_FIRST);
  91. BIND_CONSTANT(MODE_SECOND);
  92. Properties (set/get)
  93. ~~~~~~~~~~~~~~~~~~~~
  94. Objects export properties, properties are useful for the following:
  95. - Serializing and deserializing the object.
  96. - Creating a list of editable values for the Object derived class.
  97. Properties are usually defined by the PropertyInfo() class and
  98. constructed as:
  99. .. code-block:: cpp
  100. PropertyInfo(type, name, hint, hint_string, usage_flags)
  101. For example:
  102. .. code-block:: cpp
  103. PropertyInfo(Variant::INT, "amount", PROPERTY_HINT_RANGE, "0,49,1", PROPERTY_USAGE_EDITOR)
  104. This is an integer property named "amount". The hint is a range, and the range
  105. goes from 0 to 49 in steps of 1 (integers). It is only usable for the editor
  106. (editing the value visually) but won't be serialized.
  107. Another example:
  108. .. code-block:: cpp
  109. PropertyInfo(Variant::STRING, "modes", PROPERTY_HINT_ENUM, "Enabled,Disabled,Turbo")
  110. This is a string property, can take any string but the editor will only
  111. allow the defined hint ones. Since no usage flags were specified, the
  112. default ones are PROPERTY_USAGE_STORAGE and PROPERTY_USAGE_EDITOR.
  113. There are plenty of hints and usage flags available in object.h, give them a
  114. check.
  115. Properties can also work like C# properties and be accessed from script
  116. using indexing, but this usage is generally discouraged, as using
  117. functions is preferred for legibility. Many properties are also bound
  118. with categories, such as "animation/frame" which also make indexing
  119. impossible unless using operator [].
  120. From ``_bind_methods()``, properties can be created and bound as long as
  121. set/get functions exist. Example:
  122. .. code-block:: cpp
  123. ADD_PROPERTY(PropertyInfo(Variant::INT, "amount"), "set_amount", "get_amount")
  124. This creates the property using the setter and the getter.
  125. .. _doc_binding_properties_using_set_get_property_list:
  126. Binding properties using ``_set``/``_get``/``_get_property_list``
  127. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  128. An additional method of creating properties exists when more flexibility
  129. is desired (i.e. adding or removing properties on context).
  130. The following functions can be overridden in an Object derived class,
  131. they are NOT virtual, DO NOT make them virtual, they are called for
  132. every override and the previous ones are not invalidated (multilevel
  133. call).
  134. .. code-block:: cpp
  135. protected:
  136. void _get_property_list(List<PropertyInfo> *r_props) const; // return list of properties
  137. bool _get(const StringName &p_property, Variant &r_value) const; // return true if property was found
  138. bool _set(const StringName &p_property, const Variant &p_value); // return true if property was found
  139. This is also a little less efficient since ``p_property`` must be
  140. compared against the desired names in serial order.
  141. Signals
  142. ~~~~~~~
  143. Objects can have a set of signals defined (similar to Delegates in other
  144. languages). This example shows how to connect to them:
  145. .. code-block:: cpp
  146. // This is the function signature:
  147. //
  148. // Error connect(const StringName &p_signal, const Callable &p_callable, uint32_t p_flags = 0)
  149. //
  150. // For example:
  151. obj->connect("signal_name_here", callable_mp(this, &MyCustomType::method), CONNECT_DEFERRED);
  152. ``callable_mp`` is a macro to create a custom callable function pointer to member functions.
  153. For the values of ``p_flags``, see :ref:`ConnectFlags <enum_Object_ConnectFlags>`.
  154. Adding signals to a class is done in ``_bind_methods``, using the
  155. ``ADD_SIGNAL`` macro, for example:
  156. .. code-block:: cpp
  157. ADD_SIGNAL(MethodInfo("been_killed"))
  158. Object ownership and casting
  159. ----------------------------
  160. Objects are allocated on the heap. There are two different ownership models:
  161. - Objects derived from ``RefCounted`` are reference counted.
  162. - All other objects are manually memory managed.
  163. The ownership models are fundamentally different. Refer to the section for each respectively to learn how to
  164. create, store, and free the object.
  165. When you do not know whether an object passed to you (via ``Object *``) is ``RefCounted``, and you need to store it,
  166. you should store its ``ObjectID`` rather than a pointer (as explained below, in the manual memory management section).
  167. When an object is passed to you via :ref:`Variant<class_Variant>`, especially when using deferred callbacks, it is
  168. possible that the contained ``Object *`` was already freed by the time your function runs.
  169. Instead of converting directly to ``Object *``, you should use ``get_validated_object``:
  170. .. code-block:: cpp
  171. void do_something(Variant p_variant) {
  172. Object *object = p_variant.get_validated_object();
  173. ERR_FAIL_NULL(object);
  174. }
  175. Manual memory management
  176. ~~~~~~~~~~~~~~~~~~~~~~~~
  177. Manually memory managed objects are created using ``memnew`` and freed using ``memdelete``:
  178. .. code-block:: cpp
  179. Node *node = memnew(Node);
  180. // ...
  181. memdelete(node);
  182. node = nullptr;
  183. When you are not the sole owner of an object, storing a pointer to it is dangerous: The object may at any point be
  184. freed through other references to it, causing your pointer to become a dangling pointer, which will eventually result in
  185. a crash.
  186. When storing objects you are not the only owner of, you should store its ``ObjectID`` rather than a pointer:
  187. .. code-block:: cpp
  188. Node *node = memnew(Node);
  189. ObjectID node_id = node.get_instance_id();
  190. // ...
  191. Object *maybe_node = ObjectDB::get_instance(node_id);
  192. ERR_FAIL_NULL(maybe_node); // The node may have been freed between calls.
  193. ``RefCounted`` memory management
  194. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  195. :ref:`RefCounted <class_RefCounted>` subclasses are memory managed with
  196. `reference counting semantics <https://en.wikipedia.org/wiki/Reference_counting>`__.
  197. They are constructed using ``memnew``, and should be stored in ``Ref`` instances. When the last ``Ref`` instance is
  198. dropped, the object automatically self-destructs.
  199. .. code-block:: cpp
  200. class MyRefCounted: public RefCounted {
  201. GDCLASS(MyReference, RefCounted);
  202. };
  203. Ref<MyRefCounted> my_ref = memnew(MyRefCounted);
  204. // ...
  205. // Ref holds shared ownership over the object, so the object
  206. // will not be freed. As long as you have a valid, non-null
  207. // Ref, it can be safely assumed the object is still valid.
  208. my_ref->get_class_name();
  209. You should never call ``memdelete`` for ``RefCounted`` subclasses, because there may be other owners of it.
  210. You should also never store ``RefCounted`` subclasses using raw pointers, for example
  211. ``RefCounted *object = memnew(RefCounted)``. This is unsafe because other owners may destruct the object, leaving you
  212. with a dangling pointer, which will eventually result in a crash.
  213. References:
  214. ^^^^^^^^^^^
  215. - `core/object/ref_counted.h <https://github.com/godotengine/godot/blob/master/core/object/ref_counted.h>`__
  216. Dynamic casting
  217. ~~~~~~~~~~~~~~~
  218. Godot provides dynamic casting between Object-derived classes, for example:
  219. .. code-block:: cpp
  220. void some_func(Object *p_object) {
  221. Button *button = Object::cast_to<Button>(p_object);
  222. }
  223. If the cast fails, ``nullptr`` is returned. This works the same as ``dynamic_cast``, but does not use
  224. `C++ RTTI <https://en.wikipedia.org/wiki/Run-time_type_information>`__.
  225. Notifications
  226. -------------
  227. All objects in Godot have a :ref:`_notification <class_Object_private_method__notification>`
  228. method that allows them to respond to engine-level callbacks that may relate to it.
  229. More information can be found on the :ref:`doc_godot_notifications` page.
  230. Resources
  231. ----------
  232. :ref:`Resource <class_resource>` inherits from RefCounted, so all resources
  233. are reference counted. Resources can optionally contain a path, which
  234. reference a file on disk. This can be set with ``resource.set_path(path)``,
  235. though this is normally done by the resource loader. No two different
  236. resources can have the same path; attempting to do so will result in an error.
  237. Resources without a path are fine too.
  238. References:
  239. ~~~~~~~~~~~
  240. - `core/io/resource.h <https://github.com/godotengine/godot/blob/master/core/io/resource.h>`__
  241. Resource loading
  242. ~~~~~~~~~~~~~~~~
  243. Resources can be loaded with the ResourceLoader API, like this:
  244. .. code-block:: cpp
  245. Ref<Resource> res = ResourceLoader::load("res://someresource.res")
  246. If a reference to that resource has been loaded previously and is in
  247. memory, the resource loader will return that reference. This means that
  248. there can be only one resource loaded from a file referenced on disk at
  249. the same time.
  250. - resourceinteractiveloader (TODO)
  251. References:
  252. ^^^^^^^^^^^
  253. - `core/io/resource_loader.h <https://github.com/godotengine/godot/blob/master/core/io/resource_loader.h>`__
  254. Resource saving
  255. ~~~~~~~~~~~~~~~
  256. Saving a resource can be done with the resource saver API:
  257. .. code-block:: cpp
  258. ResourceSaver::save("res://someresource.res", instance)
  259. The instance will be saved, and sub resources that have a path to a file will
  260. be saved as a reference to that resource. Sub resources without a path will
  261. be bundled with the saved resource and assigned sub-IDs, like
  262. ``res://someresource.res::1``. This also helps to cache them when loaded.
  263. References:
  264. ^^^^^^^^^^^
  265. - `core/io/resource_saver.h <https://github.com/godotengine/godot/blob/master/core/io/resource_saver.h>`__