c_sharp_exports.rst 16 KB

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