c_sharp_basics.rst 16 KB

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