2
0

c_sharp_basics.rst 15 KB

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