gdscript_exports.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. .. _doc_gdscript_exports:
  2. GDScript exported properties
  3. ============================
  4. In Godot, class members can be exported. This means their value gets saved along
  5. with the resource (such as the :ref:`scene <class_PackedScene>`) they're
  6. attached to. They will also be available for editing in the property editor.
  7. Exporting is done by using the ``@export`` annotation.
  8. ::
  9. @export var number: int = 5
  10. In that example the value ``5`` will be saved and visible in the property editor.
  11. An exported variable must be initialized to a constant expression or have a type specifier
  12. in the variable. Some of the export annotations have a specific type and don't need the variable to be typed (see the
  13. *Examples* section below).
  14. One of the fundamental benefits of exporting member variables is to have
  15. them visible and editable in the editor. This way, artists and game designers
  16. can modify values that later influence how the program runs. For this, a
  17. special export syntax is provided.
  18. .. note::
  19. Exporting properties can also be done in other languages such as C#.
  20. The syntax varies depending on the language. See :ref:`doc_c_sharp_exports`
  21. for information on C# exports.
  22. Basic use
  23. ---------
  24. If the exported value assigns a constant or constant expression,
  25. the type will be inferred and used in the editor.
  26. ::
  27. @export var number = 5
  28. If there's no default value, you can add a type to the variable.
  29. ::
  30. @export var number: int
  31. Resources and nodes can be exported.
  32. ::
  33. @export var resource: Resource
  34. @export var node: Node
  35. Grouping exports
  36. ----------------
  37. It is possible to group your exported properties inside the Inspector
  38. with the :ref:`@export_group <class_@GDScript_annotation_@export_group>`
  39. annotation. Every exported property after this annotation will be added to
  40. the group. Start a new group or use ``@export_group("")`` to break out.
  41. ::
  42. @export_group("My Properties")
  43. @export var number = 3
  44. The second argument of the annotation can be used to only group properties
  45. with the specified prefix.
  46. Groups cannot be nested, use :ref:`@export_subgroup <class_@GDScript_annotation_@export_subgroup>`
  47. to create subgroups within a group.
  48. ::
  49. @export_subgroup("Extra Properties")
  50. @export var string = ""
  51. @export var flag = false
  52. You can also change the name of your main category, or create additional
  53. categories in the property list with the :ref:`@export_category <class_@GDScript_annotation_@export_category>`
  54. annotation.
  55. ::
  56. @export_category("Main Category")
  57. @export var number = 3
  58. @export var string = ""
  59. @export_category("Extra Category")
  60. @export var flag = false
  61. .. note::
  62. The list of properties is organized based on the class inheritance and
  63. new categories break that expectation. Use them carefully, especially
  64. when creating projects for public use.
  65. Strings as paths
  66. ----------------
  67. String as a path to a file.
  68. ::
  69. @export_file var f
  70. String as a path to a directory.
  71. ::
  72. @export_dir var f
  73. String as a path to a file, custom filter provided as hint.
  74. ::
  75. @export_file("*.txt") var f
  76. Using paths in the global filesystem is also possible,
  77. but only in scripts in tool mode.
  78. String as a path to a PNG file in the global filesystem.
  79. ::
  80. @export_global_file("*.png") var tool_image
  81. String as a path to a directory in the global filesystem.
  82. ::
  83. @export_global_dir var tool_dir
  84. The multiline annotation tells the editor to show a large input
  85. field for editing over multiple lines.
  86. ::
  87. @export_multiline var text
  88. Limiting editor input ranges
  89. ----------------------------
  90. Allow integer values from 0 to 20.
  91. ::
  92. @export_range(0, 20) var i
  93. Allow integer values from -10 to 20.
  94. ::
  95. @export_range(-10, 20) var j
  96. Allow floats from -10 to 20 and snap the value to multiples of 0.2.
  97. ::
  98. @export_range(-10, 20, 0.2) var k: float
  99. The limits can be made to affect only the slider if you add the hints ``"or_less"``
  100. and/or ``"or_greater"``. If either these hints are used, it will be possible for
  101. the user to enter any value or drag the value with the mouse when not using
  102. the slider, even if outside the specified range.
  103. ::
  104. @export_range(0, 100, 1, "or_less", "or_greater") var l: int
  105. The ``"exp"`` hint can be used to make a value have an exponential slider
  106. instead of a linear slider. This means that when dragging the slider towards
  107. the right, changes will become progressively faster when dragging the mouse.
  108. This is useful to make editing values that can be either very small or very large
  109. easier, at the cost of being less intuitive.
  110. ::
  111. @export_range(0, 100000, 0.01, "exp") var exponential: float
  112. For values that are meant to represent an easing factor, use
  113. :ref:`doc_gdscript_exports_floats_with_easing_hint` instead.
  114. The ``"hide_slider"`` hint can be used to hide the horizontal bar that
  115. appears below ``float`` properties, or the up/down arrows that appear besides
  116. ``int`` properties:
  117. ::
  118. @export_range(0, 1000, 0.01, "hide_slider") var no_slider: float
  119. Adding suffixes and handling degrees/radians
  120. --------------------------------------------
  121. A suffix can also be defined to make the value more self-explanatory in the
  122. inspector. For example, to define a value that is meant to be configured as
  123. "meters" (``m``) by the user:
  124. ::
  125. @export_range(0, 100, 1, "suffix:m") var m: int
  126. For angles that are stored in radians but displayed as degrees to the user, use
  127. the `"radians_as_degrees"` hint:
  128. ::
  129. @export_range(0, 360, 0.1, "radians_as_degrees") var angle: float
  130. This performs automatic conversion when the value is displayed or modified in
  131. the inspector and also displays a degree (``°``) suffix. This approach is used
  132. by Godot's own `rotation` properties throughout the editor.
  133. If the angle is stored in degrees instead, use the `"degrees"` hint to display
  134. the degree symbol while disabling the automatic degrees-to-radians conversion
  135. when the value is modified from the inspector.
  136. .. _doc_gdscript_exports_floats_with_easing_hint:
  137. Floats with easing hint
  138. -----------------------
  139. Display a visual representation of the ``ease()`` function
  140. when editing.
  141. ::
  142. @export_exp_easing var transition_speed
  143. Colors
  144. ------
  145. Regular color given as red-green-blue-alpha value.
  146. ::
  147. @export var col: Color
  148. Color given as red-green-blue value (alpha will always be 1).
  149. ::
  150. @export_color_no_alpha var col: Color
  151. Nodes
  152. -----
  153. Since Godot 4.0, nodes can be directly exported as properties in a script
  154. without having to use NodePaths:
  155. ::
  156. # Allows any node.
  157. @export var node: Node
  158. # Allows any node that inherits from BaseButton.
  159. # Custom classes declared with `class_name` can also be used.
  160. @export var some_button: BaseButton
  161. Exporting NodePaths like in Godot 3.x is still possible, in case you need it:
  162. ::
  163. @export var node_path: NodePath
  164. var node = get_node(node_path)
  165. If you want to limit the types of nodes for NodePaths, you can use the
  166. :ref:`@export_node_path<class_@GDScript_annotation_@export_node_path>`
  167. annotation:
  168. ::
  169. @export_node_path("Button", "TouchScreenButton") var some_button
  170. Resources
  171. ---------
  172. ::
  173. @export var resource: Resource
  174. In the Inspector, you can then drag and drop a resource file
  175. from the FileSystem dock into the variable slot.
  176. Opening the inspector dropdown may result in an
  177. extremely long list of possible classes to create, however.
  178. Therefore, if you specify an extension of Resource such as:
  179. ::
  180. @export var resource: AnimationNode
  181. The drop-down menu will be limited to AnimationNode and all
  182. its derived classes.
  183. It must be noted that even if the script is not being run while in the
  184. editor, the exported properties are still editable. This can be used
  185. in conjunction with a :ref:`script in "tool" mode <doc_gdscript_tool_mode>`.
  186. .. _doc_gdscript_exports_exporting_bit_flags:
  187. Exporting bit flags
  188. -------------------
  189. Integers used as bit flags can store multiple ``true``/``false`` (boolean)
  190. values in one property. By using the ``@export_flags`` annotation, they
  191. can be set from the editor::
  192. # Set any of the given flags from the editor.
  193. @export_flags("Fire", "Water", "Earth", "Wind") var spell_elements = 0
  194. You must provide a string description for each flag. In this example, ``Fire``
  195. has value 1, ``Water`` has value 2, ``Earth`` has value 4 and ``Wind``
  196. corresponds to value 8. Usually, constants should be defined accordingly (e.g.
  197. ``const ELEMENT_WIND = 8`` and so on).
  198. You can add explicit values using a colon::
  199. @export_flags("Self:4", "Allies:8", "Foes:16") var spell_targets = 0
  200. Only power of 2 values are valid as bit flags options. The lowest allowed value
  201. is 1, as 0 means that nothing is selected. You can also add options that are a
  202. combination of other flags::
  203. @export_flags("Self:4", "Allies:8", "Self and Allies:12", "Foes:16")
  204. var spell_targets = 0
  205. Export annotations are also provided for the physics, render, and navigation layers defined in the project settings::
  206. @export_flags_2d_physics var layers_2d_physics
  207. @export_flags_2d_render var layers_2d_render
  208. @export_flags_2d_navigation var layers_2d_navigation
  209. @export_flags_3d_physics var layers_3d_physics
  210. @export_flags_3d_render var layers_3d_render
  211. @export_flags_3d_navigation var layers_3d_navigation
  212. Using bit flags requires some understanding of bitwise operations.
  213. If in doubt, use boolean variables instead.
  214. Exporting enums
  215. ---------------
  216. Properties can be exported with a type hint referencing an enum to limit their values
  217. to the values of the enumeration. The editor will create a widget in the Inspector, enumerating
  218. the following as "Thing 1", "Thing 2", "Another Thing". The value will be stored as an integer.
  219. ::
  220. enum NamedEnum {THING_1, THING_2, ANOTHER_THING = -1}
  221. @export var x: NamedEnum
  222. Integer and string properties can also be limited to a specific list of values using
  223. the :ref:`@export_enum <class_@GDScript_annotation_@export_enum>` annotation.
  224. The editor will create a widget in the Inspector, enumerating the following as Warrior,
  225. Magician, Thief. The value will be stored as an integer, corresponding to the index
  226. of the selected option (i.e. ``0``, ``1``, or ``2``).
  227. ::
  228. @export_enum("Warrior", "Magician", "Thief") var character_class: int
  229. You can add explicit values using a colon::
  230. @export_enum("Slow:30", "Average:60", "Very Fast:200") var character_speed: int
  231. If the type is String, the value will be stored as a string.
  232. ::
  233. @export_enum("Rebecca", "Mary", "Leah") var character_name: String
  234. If you want to set an initial value, you must specify it explicitly::
  235. @export_enum("Rebecca", "Mary", "Leah") var character_name: String = "Rebecca"
  236. Exporting arrays
  237. ----------------
  238. Exported arrays can have initializers, but they must be constant expressions.
  239. If the exported array specifies a type which inherits from Resource, the array
  240. values can be set in the inspector by dragging and dropping multiple files
  241. from the FileSystem dock at once.
  242. The default value **must** be a constant expression.
  243. ::
  244. @export var a = [1, 2, 3]
  245. .. UPDATE: Not supported yet. When nested typed arrays are supported, update
  246. .. the example.
  247. Exported arrays can specify type (using the same hints as before).
  248. ::
  249. @export var ints: Array[int] = [1, 2, 3]
  250. # Nested typed arrays such as `Array[Array[float]]` are not supported yet.
  251. @export var two_dimensional: Array[Array] = [[1.0, 2.0], [3.0, 4.0]]
  252. You can omit the default value, but it would then be ``null`` if not assigned.
  253. ::
  254. @export var b: Array
  255. @export var scenes: Array[PackedScene]
  256. Arrays with specified types which inherit from resource can be set by
  257. drag-and-dropping multiple files from the FileSystem dock.
  258. ::
  259. @export var textures: Array[Texture] = []
  260. @export var scenes: Array[PackedScene] = []
  261. Packed type arrays also work, but only initialized empty:
  262. ::
  263. @export var vector3s = PackedVector3Array()
  264. @export var strings = PackedStringArray()
  265. Other export variants can also be used when exporting arrays:
  266. ::
  267. @export_range(-360, 360, 0.001, "degrees") var laser_angles: Array[float] = []
  268. @export_file("*.json") var skill_trees: Array[String] = []
  269. @export_color_no_alpha var hair_colors = PackedColorArray()
  270. @export_enum("Espresso", "Mocha", "Latte", "Capuccino") var barista_suggestions: Array[String] = []
  271. ``@export_storage``
  272. -------------------
  273. By default, exporting a property has two effects:
  274. 1. makes the property stored in the scene/resource file (:ref:`PROPERTY_USAGE_STORAGE <class_@GlobalScope_constant_PROPERTY_USAGE_STORAGE>`);
  275. 2. adds a field to the Inspector (:ref:`PROPERTY_USAGE_EDITOR <class_@GlobalScope_constant_PROPERTY_USAGE_EDITOR>`).
  276. However, sometimes you may want to make a property serializable, but not display it
  277. in the editor to prevent unintentional changes and cluttering the interface.
  278. To do this you can use :ref:`@export_storage <class_@GDScript_annotation_@export_storage>`.
  279. This can be useful for :ref:`@tool <class_@GDScript_annotation_@tool>` scripts.
  280. Also the property value is copied when :ref:`Resource.duplicate() <class_Resource_method_duplicate>`
  281. or :ref:`Node.duplicate() <class_Node_method_duplicate>` is called, unlike non-exported variables.
  282. ::
  283. var a # Not stored in the file, not displayed in the editor.
  284. @export_storage var b # Stored in the file, not displayed in the editor.
  285. @export var c: int # Stored in the file, displayed in the editor.
  286. ``@export_custom``
  287. ------------------
  288. If you need more control than what's exposed with the built-in ``@export``
  289. annotations, you can use ``@export_custom`` instead. This allows defining any
  290. property hint, hint string and usage flags, with a syntax similar to the one
  291. used by the editor for built-in nodes.
  292. For example, this exposes the ``altitude`` property with no range limits but a
  293. ``m`` (meter) suffix defined:
  294. ::
  295. @export_custom(PROPERTY_HINT_NONE, "altitude:m") var altitude: Vector3
  296. The above is normally not feasible with the standard ``@export_range`` syntax,
  297. since it requires defining a range.
  298. See the :ref:`class reference <class_@GDScript_annotation_@export_custom>`
  299. for a list of parameters and their allowed values.
  300. .. warning::
  301. When using ``@export_custom``, GDScript does not perform any validation on
  302. the syntax. Invalid syntax may have unexpected behavior in the inspector.
  303. ``@export_tool_button``
  304. -----------------------
  305. If you need to create a clickable inspector button, you can use ``@export_tool_button``.
  306. This exports a ``Callable`` property as a clickable button. When the button is pressed, the callable is called.
  307. Export a button with label ``"Hello"`` and icon ``"Callable"``. When you press it, it will print ``"Hello world!"``.
  308. ::
  309. @tool
  310. extends Node
  311. @export_tool_button("Hello", "Callable") var hello_action = hello
  312. func hello():
  313. print("Hello world!")
  314. Setting exported variables from a tool script
  315. ---------------------------------------------
  316. When changing an exported variable's value from a script in
  317. :ref:`doc_gdscript_tool_mode`, the value in the inspector won't be updated
  318. automatically. To update it, call
  319. :ref:`notify_property_list_changed() <class_Object_method_notify_property_list_changed>`
  320. after setting the exported variable's value.
  321. Advanced exports
  322. ----------------
  323. Not every type of export can be provided on the level of the language itself to
  324. avoid unnecessary design complexity. The following describes some more or less
  325. common exporting features which can be implemented with a low-level API.
  326. Before reading further, you should get familiar with the way properties are
  327. handled and how they can be customized with
  328. :ref:`_set() <class_Object_private_method__set>`,
  329. :ref:`_get() <class_Object_private_method__get>`, and
  330. :ref:`_get_property_list() <class_Object_private_method__get_property_list>` methods as
  331. described in :ref:`doc_accessing_data_or_logic_from_object`.
  332. .. seealso:: For binding properties using the above methods in C++, see
  333. :ref:`doc_binding_properties_using_set_get_property_list`.
  334. .. warning:: The script must operate in the ``@tool`` mode so the above methods
  335. can work from within the editor.