object_class.rst 9.2 KB

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