c_sharp_exports.rst 16 KB

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