c_sharp_basics.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. C# basics
  2. =========
  3. Introduction
  4. ------------
  5. This page provides a brief introduction to C#, both what it is and
  6. how to use it in Godot. Afterwards, you may want to look at
  7. :ref:`how to use specific features <doc_c_sharp_features>`, read about the
  8. :ref:`differences between the C# and the GDScript API <doc_c_sharp_differences>`,
  9. and (re)visit the :ref:`Scripting section <doc_scripting>` of the
  10. step-by-step tutorial.
  11. C# is a high-level programming language developed by Microsoft. In Godot,
  12. it is implemented with .NET 8.0.
  13. .. attention::
  14. Projects written in C# using Godot 4 currently cannot be exported to the web
  15. platform. To use C# on the web platform, consider Godot 3 instead.
  16. Android and iOS platform support is available as of Godot 4.2, but is
  17. experimental and :ref:`some limitations apply <doc_c_sharp_platforms>`.
  18. .. note::
  19. This is **not** a full-scale tutorial on the C# language as a whole.
  20. If you aren't already familiar with its syntax or features, see the
  21. `Microsoft C# guide <https://docs.microsoft.com/en-us/dotnet/csharp/index>`_
  22. or look for a suitable introduction elsewhere.
  23. .. _doc_c_sharp_setup:
  24. Prerequisites
  25. -------------
  26. Godot bundles the parts of .NET needed to run already compiled games.
  27. However, Godot does not bundle the tools required to build and compile
  28. games, such as MSBuild and the C# compiler. These are
  29. included in the .NET SDK, and need to be installed separately.
  30. In summary, you must have installed the .NET SDK **and** the .NET-enabled
  31. version of Godot.
  32. Download and install the latest stable version of the SDK from the
  33. `.NET download page <https://dotnet.microsoft.com/download>`__.
  34. .. important::
  35. Be sure to install the 64-bit version of the SDK(s)
  36. if you are using the 64-bit version of Godot.
  37. If you are building Godot from source, make sure to follow the steps to enable
  38. .NET support in your build as outlined in the :ref:`doc_compiling_with_dotnet`
  39. page.
  40. .. _doc_c_sharp_setup_external_editor:
  41. Configuring an external editor
  42. ------------------------------
  43. C# support in Godot's built-in script editor is minimal. Consider using an
  44. external IDE or editor, such as `Visual Studio Code <https://code.visualstudio.com/>`__
  45. or `Visual Studio <https://visualstudio.microsoft.com/>`__. These provide autocompletion, debugging, and other
  46. useful features for C#. To select an external editor in Godot,
  47. click on **Editor → Editor Settings** and scroll down to
  48. **Dotnet**. Under **Dotnet**, click on **Editor**, and select your
  49. external editor of choice. Godot currently supports the following
  50. external editors:
  51. - Visual Studio 2022
  52. - Visual Studio Code
  53. - MonoDevelop
  54. - Visual Studio for Mac
  55. - JetBrains Rider
  56. See the following sections for how to configure an external editor:
  57. JetBrains Rider
  58. ~~~~~~~~~~~~~~~
  59. After reading the "Prerequisites" section, you can download and install
  60. `JetBrains Rider <https://www.jetbrains.com/rider/download>`__.
  61. In Godot's **Editor → Editor Settings** menu:
  62. - Set **Dotnet** -> **Editor** -> **External Editor** to **JetBrains Rider**.
  63. In Rider:
  64. - Set **MSBuild version** to **.NET Core**.
  65. - If you are using a Rider version below 2024.2, install the **Godot support** plugin. This functionality is now built into Rider.
  66. Visual Studio Code
  67. ~~~~~~~~~~~~~~~~~~
  68. After reading the "Prerequisites" section, you can download and install
  69. `Visual Studio Code <https://code.visualstudio.com/download>`__ (aka VS Code).
  70. In Godot's **Editor → Editor Settings** menu:
  71. - Set **Dotnet** -> **Editor** -> **External Editor** to **Visual Studio Code**.
  72. In Visual Studio Code:
  73. - Install the `C# <https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp>`__ extension.
  74. To configure a project for debugging, you need a ``tasks.json`` and ``launch.json`` file in
  75. the ``.vscode`` folder with the necessary configuration.
  76. Here is an example ``launch.json``:
  77. .. code-block:: json
  78. {
  79. "version": "0.2.0",
  80. "configurations": [
  81. {
  82. "name": "Play",
  83. "type": "coreclr",
  84. "request": "launch",
  85. "preLaunchTask": "build",
  86. "program": "${env:GODOT4}",
  87. "args": [],
  88. "cwd": "${workspaceFolder}",
  89. "stopAtEntry": false,
  90. }
  91. ]
  92. }
  93. For this launch configuration to work, you need to either setup a GODOT4
  94. environment variable that points to the Godot executable, or replace ``program``
  95. parameter with the path to the Godot executable.
  96. Here is an example ``tasks.json``:
  97. .. code-block:: json
  98. {
  99. "version": "2.0.0",
  100. "tasks": [
  101. {
  102. "label": "build",
  103. "command": "dotnet",
  104. "type": "process",
  105. "args": [
  106. "build"
  107. ],
  108. "problemMatcher": "$msCompile"
  109. }
  110. ]
  111. }
  112. Now, when you start the debugger in Visual Studio Code, your Godot project will run.
  113. Visual Studio (Windows only)
  114. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  115. Download and install the latest version of
  116. `Visual Studio <https://visualstudio.microsoft.com/downloads/>`__.
  117. Visual Studio will include the required SDKs if you have the correct
  118. workloads selected, so you don't need to manually install the things
  119. listed in the "Prerequisites" section.
  120. While installing Visual Studio, select this workload:
  121. - .NET desktop development
  122. In Godot's **Editor → Editor Settings** menu:
  123. - Set **Dotnet** -> **Editor** -> **External Editor** to **Visual Studio**.
  124. .. note:: If you see an error like "Unable to find package Godot.NET.Sdk",
  125. your NuGet configuration may be incorrect and need to be fixed.
  126. A simple way to fix the NuGet configuration file is to regenerate it.
  127. In a file explorer window, go to ``%AppData%\NuGet``. Rename or delete
  128. the ``NuGet.Config`` file. When you build your Godot project again,
  129. the file will be automatically created with default values.
  130. To debug your C# scripts using Visual Studio, open the .sln file that is generated
  131. after opening the first C# script in the editor. In the **Debug** menu, go to the
  132. **Debug Properties** menu item for your project. Click the **Create a new profile**
  133. button and choose **Executable**. In the **Executable** field, browse to the path
  134. of the C# version of the Godot editor, or type ``%GODOT4%`` if you have created an
  135. environment variable for the Godot executable path. It must be the path to the main Godot
  136. executable, not the 'console' version. For the **Working Directory**, type a single period,
  137. ``.``, meaning the current directory. Also check the **Enable native code debugging**
  138. checkbox. You may now close this window, click downward arrow on the debug profile
  139. dropdown, and select your new launch profile. Hit the green start button, and your
  140. game will begin playing in debug mode.
  141. Creating a C# script
  142. --------------------
  143. After you successfully set up C# for Godot, you should see the following option
  144. when selecting **Attach Script** in the context menu of a node in your scene:
  145. .. image:: img/attachcsharpscript.webp
  146. Note that while some specifics change, most concepts work the same
  147. when using C# for scripting. If you're new to Godot, you may want to follow
  148. the tutorials on :ref:`doc_scripting` at this point.
  149. While some documentation pages still lack C# examples, most notions
  150. can be transferred from GDScript.
  151. Project setup and workflow
  152. --------------------------
  153. When you create the first C# script, Godot initializes the C# project files
  154. for your Godot project. This includes generating a C# solution (``.sln``)
  155. and a project file (``.csproj``), as well as some utility files and folders
  156. (``.godot/mono``).
  157. All of these but ``.godot/mono`` are important and should be committed to your
  158. version control system. Everything under ``.godot`` can be safely added to the
  159. ignore list of your VCS.
  160. When troubleshooting, it can sometimes help to delete the ``.godot/mono`` folder
  161. and let it regenerate.
  162. Example
  163. -------
  164. Here's a blank C# script with some comments to demonstrate how it works.
  165. .. code-block:: csharp
  166. using Godot;
  167. public partial class YourCustomClass : Node
  168. {
  169. // Member variables here, example:
  170. private int _a = 2;
  171. private string _b = "textvar";
  172. public override void _Ready()
  173. {
  174. // Called every time the node is added to the scene.
  175. // Initialization here.
  176. GD.Print("Hello from C# to Godot :)");
  177. }
  178. public override void _Process(double delta)
  179. {
  180. // Called every frame. Delta is time since the last frame.
  181. // Update game logic here.
  182. }
  183. }
  184. As you can see, functions normally in global scope in GDScript like Godot's
  185. ``print`` function are available in the ``GD`` static class which is part of
  186. the ``Godot`` namespace. For a full list of methods in the ``GD`` class, see the
  187. class reference pages for
  188. :ref:`@GDScript <class_@gdscript>` and :ref:`@GlobalScope <class_@globalscope>`.
  189. .. note::
  190. Keep in mind that the class you wish to attach to your node should have the same
  191. name as the ``.cs`` file. Otherwise, you will get the following error:
  192. *"Cannot find class XXX for script res://XXX.cs"*
  193. .. _doc_c_sharp_general_differences:
  194. General differences between C# and GDScript
  195. -------------------------------------------
  196. The C# API uses ``PascalCase`` instead of ``snake_case`` in GDScript/C++.
  197. Where possible, fields and getters/setters have been converted to properties.
  198. In general, the C# Godot API strives to be as idiomatic as is reasonably possible.
  199. For more information, see the :ref:`doc_c_sharp_differences` page.
  200. .. warning::
  201. You need to (re)build the project assemblies whenever you want to see new
  202. exported variables or signals in the editor. This build can be manually
  203. triggered by clicking the **Build** button in the top right corner of the
  204. editor.
  205. .. image:: img/build_dotnet.webp
  206. You will also need to rebuild the project assemblies to apply changes in
  207. "tool" scripts.
  208. Current gotchas and known issues
  209. --------------------------------
  210. As C# support is quite new in Godot, there are some growing pains and things
  211. that need to be ironed out. Below is a list of the most important issues
  212. you should be aware of when diving into C# in Godot, but if in doubt, also
  213. take a look over the official
  214. `issue tracker for .NET issues <https://github.com/godotengine/godot/labels/topic%3Adotnet>`_.
  215. - Writing editor plugins is possible, but it is currently quite convoluted.
  216. - State is currently not saved and restored when hot-reloading,
  217. with the exception of exported variables.
  218. - Attached C# scripts should refer to a class that has a class name
  219. that matches the file name.
  220. - There are some methods such as ``Get()``/``Set()``, ``Call()``/``CallDeferred()``
  221. and signal connection method ``Connect()`` that rely on Godot's ``snake_case`` API
  222. naming conventions.
  223. So when using e.g. ``CallDeferred("AddChild")``, ``AddChild`` will not work because
  224. the API is expecting the original ``snake_case`` version ``add_child``. However, you
  225. can use any custom properties or methods without this limitation.
  226. Prefer using the exposed ``StringName`` in the ``PropertyName``, ``MethodName`` and
  227. ``SignalName`` to avoid extra ``StringName`` allocations and worrying about snake_case naming.
  228. As of Godot 4.0, exporting .NET projects is supported for desktop platforms
  229. (Linux, Windows and macOS). Other platforms will gain support in future 4.x
  230. releases.
  231. Common pitfalls
  232. ---------------
  233. You might encounter the following error when trying to modify some values in Godot
  234. objects, e.g. when trying to change the X coordinate of a ``Node2D``:
  235. .. code-block:: csharp
  236. :emphasize-lines: 5
  237. public partial class MyNode2D : Node2D
  238. {
  239. public override void _Ready()
  240. {
  241. Position.X = 100.0f;
  242. // CS1612: Cannot modify the return value of 'Node2D.Position' because
  243. // it is not a variable.
  244. }
  245. }
  246. This is perfectly normal. Structs (in this example, a ``Vector2``) in C# are
  247. copied on assignment, meaning that when you retrieve such an object from a
  248. property or an indexer, you get a copy of it, not the object itself. Modifying
  249. said copy without reassigning it afterwards won't achieve anything.
  250. The workaround is simple: retrieve the entire struct, modify the value you want
  251. to modify, and reassign the property.
  252. .. code-block:: csharp
  253. var newPosition = Position;
  254. newPosition.X = 100.0f;
  255. Position = newPosition;
  256. Since C# 10, it is also possible to use `with expressions <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression>`_
  257. on structs, allowing you to do the same thing in a single line.
  258. .. code-block:: csharp
  259. Position = Position with { X = 100.0f };
  260. You can read more about this error on the `C# language reference <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1612>`_.
  261. Performance of C# in Godot
  262. --------------------------
  263. .. seealso::
  264. For a performance comparison of the languages Godot supports,
  265. see :ref:`doc_faq_which_programming_language_is_fastest`.
  266. Most properties of Godot C# objects that are based on ``GodotObject``
  267. (e.g. any ``Node`` like ``Control`` or ``Node3D`` like ``Camera3D``) require native (interop) calls as they talk to
  268. Godot's C++ core.
  269. Consider assigning values of such properties into a local variable if you need to modify or read them multiple times at
  270. a single code location:
  271. .. code-block:: csharp
  272. using Godot;
  273. public partial class YourCustomClass : Node3D
  274. {
  275. private void ExpensiveReposition()
  276. {
  277. for (var i = 0; i < 10; i++)
  278. {
  279. // Position is read and set 10 times which incurs native interop.
  280. // Furthermore the object is repositioned 10 times in 3D space which
  281. // takes additional time.
  282. Position += new Vector3(i, i);
  283. }
  284. }
  285. private void Reposition()
  286. {
  287. // A variable is used to avoid native interop for Position on every loop.
  288. var newPosition = Position;
  289. for (var i = 0; i < 10; i++)
  290. {
  291. newPosition += new Vector3(i, i);
  292. }
  293. // Setting Position only once avoids native interop and repositioning in 3D space.
  294. Position = newPosition;
  295. }
  296. }
  297. Passing raw arrays (such as ``byte[]``) or ``string`` to Godot's C# API requires marshalling which is
  298. comparatively pricey.
  299. The implicit conversion from ``string`` to ``NodePath`` or ``StringName`` incur both the native interop and marshalling
  300. costs as the ``string`` has to be marshalled and passed to the respective native constructor.
  301. Using NuGet packages in Godot
  302. -----------------------------
  303. `NuGet <https://www.nuget.org/>`_ packages can be installed and used with Godot,
  304. as with any C# project. Many IDEs are able to add packages directly.
  305. They can also be added manually by adding the package reference in
  306. the ``.csproj`` file located in the project root:
  307. .. code-block:: xml
  308. :emphasize-lines: 2
  309. <ItemGroup>
  310. <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
  311. </ItemGroup>
  312. ...
  313. </Project>
  314. As of Godot 3.2.3, Godot automatically downloads and sets up newly added NuGet
  315. packages the next time it builds the project.
  316. Profiling your C# code
  317. ----------------------
  318. The following tools may be used for performance and memory profiling of your managed code:
  319. - JetBrains Rider with dotTrace/dotMemory plugin.
  320. - Standalone JetBrains dotTrace/dotMemory.
  321. - Visual Studio.
  322. Profiling managed and unmanaged code at once is possible with both JetBrains tools and Visual Studio, but limited to Windows.