object_class.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. Objects provide reflection and
  11. editable properties, and declaring them is a matter of using a single
  12. macro like this:
  13. .. code-block:: cpp
  14. class CustomObject : public Object {
  15. GDCLASS(CustomObject, Object); // this is required to inherit
  16. };
  17. This adds a lot of functionality to Objects. For example:
  18. .. code-block:: cpp
  19. obj = memnew(CustomObject);
  20. print_line("Object class: ", obj->get_class()); // print object class
  21. obj2 = Object::cast_to<OtherClass>(obj); // converting between classes, this also works without RTTI enabled.
  22. References:
  23. ~~~~~~~~~~~
  24. - `core/object/object.h <https://github.com/godotengine/godot/blob/master/core/object/object.h>`__
  25. Registering an Object
  26. ---------------------
  27. ClassDB is a static class that holds the entire list of registered
  28. classes that inherit from Object, as well as dynamic bindings to all
  29. their methods properties and integer constants.
  30. Classes are registered by calling:
  31. .. code-block:: cpp
  32. ClassDB::register_class<MyCustomClass>()
  33. Registering it will allow the class to be instanced by scripts, code, or
  34. creating them again when deserializing.
  35. Registering as virtual is the same but it can't be instanced.
  36. .. code-block:: cpp
  37. ClassDB::register_virtual_class<MyCustomClass>()
  38. Object-derived classes can override the static function
  39. ``static void _bind_methods()``. When one class is registered, this
  40. static function is called to register all the object methods,
  41. properties, constants, etc. It's only called once. If an Object derived
  42. class is instanced but has not been registered, it will be registered as
  43. virtual automatically.
  44. Inside ``_bind_methods``, there are a couple of things that can be done.
  45. Registering functions is one:
  46. .. code-block:: cpp
  47. ClassDB::bind_method(D_METHOD("methodname", "arg1name", "arg2name", "arg3name"), &MyCustomType::method);
  48. Default values for arguments can be passed as parameters at the end:
  49. .. code-block:: cpp
  50. ClassDB::bind_method(D_METHOD("methodname", "arg1name", "arg2name", "arg3name"), &MyCustomType::method, DEFVAL(-1), DEFVAL(-2)); // Default values for arg2name (-1) and arg3name (-2).
  51. Default values must be provided in the same order as they are declared,
  52. skipping required arguments and then providing default values for the optional ones.
  53. This matches the syntax for declaring methods in C++.
  54. ``D_METHOD`` is a macro that converts "methodname" to a StringName for more
  55. efficiency. Argument names are used for introspection, but when
  56. compiling on release, the macro ignores them, so the strings are unused
  57. and optimized away.
  58. Check ``_bind_methods`` of Control or Object for more examples.
  59. If just adding modules and functionality that is not expected to be
  60. documented as thoroughly, the ``D_METHOD()`` macro can safely be ignored and a
  61. string passing the name can be passed for brevity.
  62. References:
  63. ~~~~~~~~~~~
  64. - `core/object/class_db.h <https://github.com/godotengine/godot/blob/master/core/object/class_db.h>`__
  65. Constants
  66. ---------
  67. Classes often have enums such as:
  68. .. code-block:: cpp
  69. enum SomeMode {
  70. MODE_FIRST,
  71. MODE_SECOND
  72. };
  73. For these to work when binding to methods, the enum must be declared
  74. convertible to int. A macro is provided to help with this:
  75. .. code-block:: cpp
  76. VARIANT_ENUM_CAST(MyClass::SomeMode); // now functions that take SomeMode can be bound.
  77. The constants can also be bound inside ``_bind_methods``, by using:
  78. .. code-block:: cpp
  79. BIND_CONSTANT(MODE_FIRST);
  80. BIND_CONSTANT(MODE_SECOND);
  81. Properties (set/get)
  82. --------------------
  83. Objects export properties, properties are useful for the following:
  84. - Serializing and deserializing the object.
  85. - Creating a list of editable values for the Object derived class.
  86. Properties are usually defined by the PropertyInfo() class and
  87. constructed as:
  88. .. code-block:: cpp
  89. PropertyInfo(type, name, hint, hint_string, usage_flags)
  90. For example:
  91. .. code-block:: cpp
  92. PropertyInfo(Variant::INT, "amount", PROPERTY_HINT_RANGE, "0,49,1", PROPERTY_USAGE_EDITOR)
  93. This is an integer property named "amount". The hint is a range, and the range
  94. goes from 0 to 49 in steps of 1 (integers). It is only usable for the editor
  95. (editing the value visually) but won't be serialized.
  96. Another example:
  97. .. code-block:: cpp
  98. PropertyInfo(Variant::STRING, "modes", PROPERTY_HINT_ENUM, "Enabled,Disabled,Turbo")
  99. This is a string property, can take any string but the editor will only
  100. allow the defined hint ones. Since no usage flags were specified, the
  101. default ones are PROPERTY_USAGE_STORAGE and PROPERTY_USAGE_EDITOR.
  102. There are plenty of hints and usage flags available in object.h, give them a
  103. check.
  104. Properties can also work like C# properties and be accessed from script
  105. using indexing, but this usage is generally discouraged, as using
  106. functions is preferred for legibility. Many properties are also bound
  107. with categories, such as "animation/frame" which also make indexing
  108. impossible unless using operator [].
  109. From ``_bind_methods()``, properties can be created and bound as long as
  110. set/get functions exist. Example:
  111. .. code-block:: cpp
  112. ADD_PROPERTY(PropertyInfo(Variant::INT, "amount"), "set_amount", "get_amount")
  113. This creates the property using the setter and the getter.
  114. .. _doc_binding_properties_using_set_get_property_list:
  115. Binding properties using ``_set``/``_get``/``_get_property_list``
  116. -----------------------------------------------------------------
  117. An additional method of creating properties exists when more flexibility
  118. is desired (i.e. adding or removing properties on context).
  119. The following functions can be overridden in an Object derived class,
  120. they are NOT virtual, DO NOT make them virtual, they are called for
  121. every override and the previous ones are not invalidated (multilevel
  122. call).
  123. .. code-block:: cpp
  124. protected:
  125. void _get_property_list(List<PropertyInfo> *r_props) const; // return list of properties
  126. bool _get(const StringName &p_property, Variant &r_value) const; // return true if property was found
  127. bool _set(const StringName &p_property, const Variant &p_value); // return true if property was found
  128. This is also a little less efficient since ``p_property`` must be
  129. compared against the desired names in serial order.
  130. Dynamic casting
  131. ---------------
  132. Godot provides dynamic casting between Object-derived classes, for
  133. example:
  134. .. code-block:: cpp
  135. void somefunc(Object *some_obj) {
  136. Button *button = Object::cast_to<Button>(some_obj);
  137. }
  138. If cast fails, NULL is returned. This system uses RTTI, but it also
  139. works fine (although a bit slower) when RTTI is disabled. This is useful
  140. on platforms where a small binary size is ideal, such as HTML5 or
  141. consoles (with low memory footprint).
  142. Signals
  143. -------
  144. Objects can have a set of signals defined (similar to Delegates in other
  145. languages). This example shows how to connect to them:
  146. .. code-block:: cpp
  147. obj->connect(<signal>, target_instance, target_method)
  148. // for example:
  149. obj->connect("enter_tree", this, "_node_entered_tree")
  150. The method ``_node_entered_tree`` must be registered to the class using
  151. ``ClassDB::bind_method`` (explained before).
  152. Adding signals to a class is done in ``_bind_methods``, using the
  153. ``ADD_SIGNAL`` macro, for example:
  154. .. code-block:: cpp
  155. ADD_SIGNAL(MethodInfo("been_killed"))
  156. Notifications
  157. -------------
  158. All objects in Godot have a :ref:`_notification <class_Object_private_method__notification>`
  159. method that allows it to respond to engine level callbacks that may relate to it.
  160. More information can be found on the :ref:`doc_godot_notifications` page.
  161. References
  162. ----------
  163. :ref:`RefCounted <class_RefCounted>` inherits from Object and holds a
  164. reference count. It is the base for reference counted object types.
  165. Declaring them must be done using Ref<> template. For example:
  166. .. code-block:: cpp
  167. class MyReference: public RefCounted {
  168. GDCLASS(MyReference, RefCounted);
  169. };
  170. Ref<MyReference> myref(memnew(MyReference));
  171. ``myref`` is reference counted. It will be freed when no more Ref<>
  172. templates point to it.
  173. References:
  174. ~~~~~~~~~~~
  175. - `core/object/reference.h <https://github.com/godotengine/godot/blob/master/core/object/ref_counted.h>`__
  176. Resources
  177. ----------
  178. :ref:`Resource <class_resource>` inherits from Reference, so all resources
  179. are reference counted. Resources can optionally contain a path, which
  180. reference a file on disk. This can be set with ``resource.set_path(path)``,
  181. though this is normally done by the resource loader. No two different
  182. resources can have the same path; attempting to do so will result in an error.
  183. Resources without a path are fine too.
  184. References:
  185. ~~~~~~~~~~~
  186. - `core/io/resource.h <https://github.com/godotengine/godot/blob/master/core/io/resource.h>`__
  187. Resource loading
  188. ----------------
  189. Resources can be loaded with the ResourceLoader API, like this:
  190. .. code-block:: cpp
  191. Ref<Resource> res = ResourceLoader::load("res://someresource.res")
  192. If a reference to that resource has been loaded previously and is in
  193. memory, the resource loader will return that reference. This means that
  194. there can be only one resource loaded from a file referenced on disk at
  195. the same time.
  196. - resourceinteractiveloader (TODO)
  197. References:
  198. ~~~~~~~~~~~
  199. - `core/io/resource_loader.h <https://github.com/godotengine/godot/blob/master/core/io/resource_loader.h>`__
  200. Resource saving
  201. ---------------
  202. Saving a resource can be done with the resource saver API:
  203. .. code-block:: cpp
  204. ResourceSaver::save("res://someresource.res", instance)
  205. The instance will be saved, and sub resources that have a path to a file will
  206. be saved as a reference to that resource. Sub resources without a path will
  207. be bundled with the saved resource and assigned sub-IDs, like
  208. ``res://someresource.res::1``. This also helps to cache them when loaded.
  209. References:
  210. ~~~~~~~~~~~
  211. - `core/io/resource_saver.h <https://github.com/godotengine/godot/blob/master/core/io/resource_saver.h>`__