c_sharp_exports.rst 16 KB

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