c_sharp_exports.rst 15 KB

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