c_sharp_basics.rst 15 KB

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