c_sharp_exports.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. .. _doc_c_sharp_exports:
  2. C# 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]`` attribute.
  8. .. code-block:: csharp
  9. using Godot;
  10. public partial class ExportExample : Node3D
  11. {
  12. [Export]
  13. public int Number { get; set; } = 5;
  14. }
  15. In that example the value ``5`` will be saved, and after building the current project
  16. it will be visible in the property editor.
  17. One of the fundamental benefits of exporting member variables is to have
  18. them visible and editable in the editor. This way, artists and game designers
  19. can modify values that later influence how the program runs. For this, a
  20. special export syntax is provided.
  21. Exporting can only be done with :ref:`c_sharp_variant_compatible_types`.
  22. .. note::
  23. Exporting properties can also be done in GDScript, for information on that
  24. see :ref:`doc_gdscript_exports`.
  25. Basic use
  26. ---------
  27. Exporting works with fields and properties. They can have any access modifier.
  28. .. code-block:: csharp
  29. [Export]
  30. private int _number;
  31. [Export]
  32. public int Number { get; set; }
  33. Exported members can specify a default value; otherwise, the `default value of the type <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/default-values>`_ is used instead.
  34. An ``int`` like ``Number`` defaults to ``0``. ``Text`` defaults to null because
  35. ``string`` is a reference type.
  36. .. code-block:: csharp
  37. [Export]
  38. public int Number { get; set; }
  39. [Export]
  40. public string Text { get; set; }
  41. Default values can be specified for fields and properties.
  42. .. code-block:: csharp
  43. [Export]
  44. private string _greeting = "Hello World";
  45. [Export]
  46. public string Greeting { get; set; } = "Hello World";
  47. Properties with a backing field use the default value of the backing field.
  48. .. code-block:: csharp
  49. private int _number = 2;
  50. [Export]
  51. public int NumberWithBackingField
  52. {
  53. get => _number;
  54. set => _number = value;
  55. }
  56. .. note::
  57. A property's ``get`` is not actually executed to determine the default
  58. value. Instead, Godot analyzes the C# source code. This works fine for most
  59. cases, such as the examples on this page. However, some properties are too
  60. complex for the analyzer to understand.
  61. For example, the following property attempts to use math to display the
  62. default value as ``5`` in the property editor, but it doesn't work:
  63. .. code-block:: csharp
  64. [Export]
  65. public int NumberWithBackingField
  66. {
  67. get => _number + 3;
  68. set => _number = value - 3;
  69. }
  70. private int _number = 2;
  71. The analyzer doesn't understand this code and falls back to the default
  72. value for ``int``, ``0``. However, when running the scene or inspecting a
  73. node with an attached tool script, ``_number`` will be ``2``, and
  74. ``NumberWithBackingField`` will return ``5``. This difference may cause
  75. confusing behavior. To avoid this, don't use complex properties. Alternatively,
  76. if the default value can be explicitly specified, it can be overridden with the
  77. :ref:`_PropertyCanRevert() <class_Object_private_method__property_can_revert>` and
  78. :ref:`_PropertyGetRevert() <class_Object_private_method__property_get_revert>` methods.
  79. Any type of ``Resource`` or ``Node`` can be exported. The property editor shows
  80. a user-friendly assignment dialog for these types. This can be used instead of
  81. ``GD.Load`` and ``GetNode``. See :ref:`Nodes and Resources <doc_c_sharp_exports_nodes>`.
  82. .. code-block:: csharp
  83. [Export]
  84. public PackedScene PackedScene { get; set; }
  85. [Export]
  86. public RigidBody2D RigidBody2D { get; set; }
  87. Grouping exports
  88. ----------------
  89. It is possible to group your exported properties inside the Inspector with the ``[ExportGroup]``
  90. attribute. Every exported property after this attribute will be added to the group. Start a new
  91. group or use ``[ExportGroup("")]`` to break out.
  92. .. code-block:: csharp
  93. [ExportGroup("My Properties")]
  94. [Export]
  95. public int Number { get; set; } = 3;
  96. The second argument of the attribute can be used to only group properties with the specified prefix.
  97. Groups cannot be nested, use ``[ExportSubgroup]`` to create subgroups within a group.
  98. .. code-block:: csharp
  99. [ExportSubgroup("Extra Properties")]
  100. [Export]
  101. public string Text { get; set; } = "";
  102. [Export]
  103. public bool Flag { get; set; } = false;
  104. You can also change the name of your main category, or create additional categories in the property
  105. list with the ``[ExportCategory]`` attribute.
  106. .. code-block:: csharp
  107. [ExportCategory("Main Category")]
  108. [Export]
  109. public int Number { get; set; } = 3;
  110. [Export]
  111. public string Text { get; set; } = "";
  112. [ExportCategory("Extra Category")]
  113. [Export]
  114. public bool Flag { get; set; } = false;
  115. .. note::
  116. The list of properties is organized based on the class inheritance, and new categories break
  117. that expectation. Use them carefully, especially when creating projects for public use.
  118. Strings as paths
  119. ----------------
  120. Property hints can be used to export strings as paths
  121. String as a path to a file.
  122. .. code-block:: csharp
  123. [Export(PropertyHint.File)]
  124. public string GameFile { get; set; }
  125. String as a path to a directory.
  126. .. code-block:: csharp
  127. [Export(PropertyHint.Dir)]
  128. public string GameDirectory { get; set; }
  129. String as a path to a file, custom filter provided as hint.
  130. .. code-block:: csharp
  131. [Export(PropertyHint.File, "*.txt,")]
  132. public string GameFile { get; set; }
  133. Using paths in the global filesystem is also possible,
  134. but only in scripts in tool mode.
  135. String as a path to a PNG file in the global filesystem.
  136. .. code-block:: csharp
  137. [Export(PropertyHint.GlobalFile, "*.png")]
  138. public string ToolImage { get; set; }
  139. String as a path to a directory in the global filesystem.
  140. .. code-block:: csharp
  141. [Export(PropertyHint.GlobalDir)]
  142. public string ToolDir { get; set; }
  143. The multiline annotation tells the editor to show a large input
  144. field for editing over multiple lines.
  145. .. code-block:: csharp
  146. [Export(PropertyHint.MultilineText)]
  147. public string Text { get; set; }
  148. Limiting editor input ranges
  149. ----------------------------
  150. Using the range property hint allows you to limit what can be
  151. input as a value using the editor.
  152. Allow integer values from 0 to 20.
  153. .. code-block:: csharp
  154. [Export(PropertyHint.Range, "0,20,")]
  155. public int Number { get; set; }
  156. Allow integer values from -10 to 20.
  157. .. code-block:: csharp
  158. [Export(PropertyHint.Range, "-10,20,")]
  159. public int Number { get; set; }
  160. Allow floats from -10 to 20 and snap the value to multiples of 0.2.
  161. .. code-block:: csharp
  162. [Export(PropertyHint.Range, "-10,20,0.2")]
  163. public float Number { get; set; }
  164. If you add the hints "or_greater" and/or "or_less" you can go above
  165. or below the limits when adjusting the value by typing it instead of using
  166. the slider.
  167. .. code-block:: csharp
  168. [Export(PropertyHint.Range, "0,100,1,or_greater,or_less")]
  169. public int Number { get; set; }
  170. Floats with easing hint
  171. -----------------------
  172. Display a visual representation of the :ref:`ease<class_@GlobalScope_method_ease>`
  173. function when editing.
  174. .. code-block:: csharp
  175. [Export(PropertyHint.ExpEasing)]
  176. public float TransitionSpeed { get; set; }
  177. Export with suffix hint
  178. -----------------------
  179. Display a unit hint suffix for exported variables. Works with numeric types,
  180. such as floats or vectors:
  181. .. code-block:: csharp
  182. [Export(PropertyHint.None, "suffix:m/s\u00b2")]
  183. public float Gravity { get; set; } = 9.8f;
  184. [Export(PropertyHint.None, "suffix:m/s")]
  185. public Vector3 Velocity { get; set; }
  186. In the above example, ``\u00b2`` is used to write the "squared" character
  187. (``²``).
  188. Colors
  189. ------
  190. Regular color given as red-green-blue-alpha value.
  191. .. code-block:: csharp
  192. [Export]
  193. public Color Color { get; set; }
  194. Color given as red-green-blue value (alpha will always be 1).
  195. .. code-block:: csharp
  196. [Export(PropertyHint.ColorNoAlpha)]
  197. public Color Color { get; set; }
  198. .. _doc_c_sharp_exports_nodes:
  199. Nodes
  200. -----
  201. Since Godot 4.0, nodes can be directly exported without having to use NodePaths.
  202. .. code-block:: csharp
  203. [Export]
  204. public Node Node { get; set; }
  205. A specific type of node can also be directly exported. The list of nodes shown
  206. after pressing "Assign" in the inspector is filtered to the specified type, and
  207. only a correct node can be assigned.
  208. .. code-block:: csharp
  209. [Export]
  210. public Sprite2D Sprite2D { get; set; }
  211. Custom node classes can also be exported directly. The filtering behavior
  212. depends on whether the custom class is a
  213. :ref:`global class <doc_c_sharp_global_classes>`.
  214. Exporting NodePaths like in Godot 3.x is still possible, in case you need it:
  215. .. code-block:: csharp
  216. [Export]
  217. public NodePath NodePath { get; set; }
  218. public override void _Ready()
  219. {
  220. var node = GetNode(NodePath);
  221. }
  222. Resources
  223. ---------
  224. .. code-block:: csharp
  225. [Export]
  226. public Resource Resource { get; set; }
  227. In the Inspector, you can then drag and drop a resource file
  228. from the FileSystem dock into the variable slot.
  229. Opening the inspector dropdown may result in an
  230. extremely long list of possible classes to create, however.
  231. Therefore, if you specify a type derived from Resource such as:
  232. .. code-block:: csharp
  233. [Export]
  234. public AnimationNode AnimationNode { get; set; }
  235. The drop-down menu will be limited to AnimationNode and all
  236. its inherited classes. Custom resource classes can also be used,
  237. see :ref:`doc_c_sharp_global_classes`.
  238. It must be noted that even if the script is not being run while in the
  239. editor, the exported properties are still editable. This can be used
  240. in conjunction with a :ref:`script in "tool" mode <doc_gdscript_tool_mode>`.
  241. Exporting bit flags
  242. -------------------
  243. Members whose type is an enum with the ``[Flags]`` attribute can be exported and
  244. their values are limited to the members of the enum type.
  245. The editor will create a widget in the Inspector, allowing to select none, one,
  246. or multiple of the enum members. The value will be stored as an integer.
  247. A flags enum uses powers of 2 for the values of the enum members. Members that
  248. combine multiple flags using logical OR (``|``) are also possible.
  249. .. code-block:: csharp
  250. [Flags]
  251. public enum SpellElements
  252. {
  253. Fire = 1 << 1,
  254. Water = 1 << 2,
  255. Earth = 1 << 3,
  256. Wind = 1 << 4,
  257. FireAndWater = Fire | Water,
  258. }
  259. [Export]
  260. public SpellElements MySpellElements { get; set; }
  261. Integers used as bit flags can store multiple ``true``/``false`` (boolean)
  262. values in one property. By using the ``Flags`` property hint, any of the given
  263. flags can be set from the editor.
  264. .. code-block:: csharp
  265. [Export(PropertyHint.Flags, "Fire,Water,Earth,Wind")]
  266. public int SpellElements { get; set; } = 0;
  267. You must provide a string description for each flag. In this example, ``Fire``
  268. has value 1, ``Water`` has value 2, ``Earth`` has value 4 and ``Wind``
  269. corresponds to value 8. Usually, constants should be defined accordingly (e.g.
  270. ``private const int ElementWind = 8`` and so on).
  271. You can add explicit values using a colon:
  272. .. code-block:: csharp
  273. [Export(PropertyHint.Flags, "Self:4,Allies:8,Foes:16")]
  274. public int SpellTargets { get; set; } = 0;
  275. Only power of 2 values are valid as bit flags options. The lowest allowed value
  276. is 1, as 0 means that nothing is selected. You can also add options that are a
  277. combination of other flags:
  278. .. code-block:: csharp
  279. [Export(PropertyHint.Flags, "Self:4,Allies:8,Self and Allies:12,Foes:16")]
  280. public int SpellTargets { get; set; } = 0;
  281. Export annotations are also provided for the physics and render layers defined in the project settings.
  282. .. code-block:: csharp
  283. [Export(PropertyHint.Layers2DPhysics)]
  284. public uint Layers2DPhysics { get; set; }
  285. [Export(PropertyHint.Layers2DRender)]
  286. public uint Layers2DRender { get; set; }
  287. [Export(PropertyHint.Layers3DPhysics)]
  288. public uint Layers3DPhysics { get; set; }
  289. [Export(PropertyHint.Layers3DRender)]
  290. public uint Layers3DRender { get; set; }
  291. Using bit flags requires some understanding of bitwise operations.
  292. If in doubt, use boolean variables instead.
  293. Exporting enums
  294. ---------------
  295. Members whose type is an enum can be exported and their values are limited to the members
  296. of the enum type. The editor will create a widget in the Inspector, enumerating the
  297. following as "Thing 1", "Thing 2", "Another Thing". The value will be stored as an integer.
  298. .. code-block:: csharp
  299. public enum MyEnum
  300. {
  301. Thing1,
  302. Thing2,
  303. AnotherThing = -1,
  304. }
  305. [Export]
  306. public MyEnum MyEnum { get; set; }
  307. Integer and string members can also be limited to a specific list of values using the
  308. ``[Export]`` annotation with the ``PropertyHint.Enum`` hint.
  309. The editor will create a widget in the Inspector, enumerating the following as Warrior,
  310. Magician, Thief. The value will be stored as an integer, corresponding to the index
  311. of the selected option (i.e. ``0``, ``1``, or ``2``).
  312. .. code-block:: csharp
  313. [Export(PropertyHint.Enum, "Warrior,Magician,Thief")]
  314. public int CharacterClass { get; set; }
  315. You can add explicit values using a colon:
  316. .. code-block:: csharp
  317. [Export(PropertyHint.Enum, "Slow:30,Average:60,Very Fast:200")]
  318. public int CharacterSpeed { get; set; }
  319. If the type is ``string``, the value will be stored as a string.
  320. .. code-block:: csharp
  321. [Export(PropertyHint.Enum, "Rebecca,Mary,Leah")]
  322. public string CharacterName { get; set; }
  323. If you want to set an initial value, you must specify it explicitly:
  324. .. code-block:: csharp
  325. [Export(PropertyHint.Enum, "Rebecca,Mary,Leah")]
  326. public string CharacterName { get; set; } = "Rebecca";
  327. Exporting collections
  328. ---------------------
  329. As explained in the :ref:`C# Variant <doc_c_sharp_variant>` documentation, only
  330. certain C# arrays and the collection types defined in the ``Godot.Collections``
  331. namespace are Variant-compatible, therefore, only those types can be exported.
  332. Exporting Godot arrays
  333. ^^^^^^^^^^^^^^^^^^^^^^
  334. .. code-block:: csharp
  335. [Export]
  336. public Godot.Collections.Array Array { get; set; }
  337. Using the generic ``Godot.Collections.Array<T>`` allows specifying the type of the
  338. array elements, which will be used as a hint for the editor. The Inspector will
  339. restrict the elements to the specified type.
  340. .. code-block:: csharp
  341. [Export]
  342. public Godot.Collections.Array<string> Array { get; set; }
  343. The default value of Godot arrays is null. A different default can be specified:
  344. .. code-block:: csharp
  345. [Export]
  346. public Godot.Collections.Array<string> CharacterNames { get; set; } = new Godot.Collections.Array<string>
  347. {
  348. "Rebecca",
  349. "Mary",
  350. "Leah",
  351. };
  352. Arrays with specified types which inherit from resource can be set by
  353. drag-and-dropping multiple files from the FileSystem dock.
  354. .. code-block:: csharp
  355. [Export]
  356. public Godot.Collections.Array<Texture> Textures { get; set; }
  357. [Export]
  358. public Godot.Collections.Array<PackedScene> Scenes { get; set; }
  359. Exporting Godot dictionaries
  360. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  361. .. code-block:: csharp
  362. [Export]
  363. public Godot.Collections.Dictionary Dictionary { get; set; }
  364. Using the generic ``Godot.Collections.Dictionary<TKey, TValue>`` allows specifying
  365. the types of the key and value elements of the dictionary.
  366. .. note::
  367. Typed dictionaries are currently unsupported in the Godot editor, so
  368. the Inspector will not restrict the types that can be assigned, potentially
  369. resulting in runtime exceptions.
  370. .. code-block:: csharp
  371. [Export]
  372. public Godot.Collections.Dictionary<string, int> Dictionary { get; set; }
  373. The default value of Godot dictionaries is null. A different default can be specified:
  374. .. code-block:: csharp
  375. [Export]
  376. public Godot.Collections.Dictionary<string, int> CharacterLives { get; set; } = new Godot.Collections.Dictionary<string, int>
  377. {
  378. ["Rebecca"] = 10,
  379. ["Mary"] = 42,
  380. ["Leah"] = 0,
  381. };
  382. Exporting C# arrays
  383. ^^^^^^^^^^^^^^^^^^^
  384. C# arrays can exported as long as the element type is a :ref:`Variant-compatible type <c_sharp_variant_compatible_types>`.
  385. .. code-block:: csharp
  386. [Export]
  387. public Vector3[] Vectors { get; set; }
  388. [Export]
  389. public NodePath[] NodePaths { get; set; }
  390. The default value of C# arrays is null. A different default can be specified:
  391. .. code-block:: csharp
  392. [Export]
  393. public Vector3[] Vectors { get; set; } = new Vector3[]
  394. {
  395. new Vector3(1, 2, 3),
  396. new Vector3(3, 2, 1),
  397. }
  398. Setting exported variables from a tool script
  399. ---------------------------------------------
  400. When changing an exported variable's value from a script in
  401. :ref:`doc_gdscript_tool_mode`, the value in the inspector won't be updated
  402. automatically. To update it, call
  403. :ref:`NotifyPropertyListChanged() <class_Object_method_notify_property_list_changed>`
  404. after setting the exported variable's value.
  405. Advanced exports
  406. ----------------
  407. Not every type of export can be provided on the level of the language itself to
  408. avoid unnecessary design complexity. The following describes some more or less
  409. common exporting features which can be implemented with a low-level API.
  410. Before reading further, you should get familiar with the way properties are
  411. handled and how they can be customized with
  412. :ref:`_Set() <class_Object_private_method__set>`,
  413. :ref:`_Get() <class_Object_private_method__get>`, and
  414. :ref:`_GetPropertyList() <class_Object_private_method__get_property_list>` methods as
  415. described in :ref:`doc_accessing_data_or_logic_from_object`.
  416. .. seealso:: For binding properties using the above methods in C++, see
  417. :ref:`doc_binding_properties_using_set_get_property_list`.
  418. .. warning:: The script must operate in the ``tool`` mode so the above methods
  419. can work from within the editor.