c_sharp_basics.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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
  37. `.NET Core SDK <https://dotnet.microsoft.com/download/dotnet-core>`__
  38. (3.1 as of writing).
  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 include the tools required to build and compile
  43. games, such as MSBuild. These tools need to be installed separately.
  44. The required tools are included in the .NET Core SDK. MSBuild is also
  45. included in the Mono SDK, but it can't build C# projects with the new
  46. ``csproj`` format, therefore .NET Core SDK is required for Godot 3.2.3+.
  47. In summary, you must have installed .NET Core SDK
  48. **and** the Mono-enabled version of Godot.
  49. Additional notes
  50. ~~~~~~~~~~~~~~~~
  51. Be sure to install the 64-bit version of the SDK(s)
  52. if you are using the 64-bit version of Godot.
  53. If you are building Godot from source, install the latest stable version of
  54. `Mono <https://www.mono-project.com/download/stable/>`__, and make sure to
  55. follow the steps to enable Mono support in your build as outlined in the
  56. :ref:`doc_compiling_with_mono` page.
  57. Configuring an external editor
  58. ------------------------------
  59. C# support in Godot's built-in script editor is minimal. Consider using an
  60. external IDE or editor, such as `Visual Studio Code <https://code.visualstudio.com/>`__
  61. or MonoDevelop. These provide autocompletion, debugging, and other
  62. useful features for C#. To select an external editor in Godot,
  63. click on **Editor → Editor Settings** and scroll down to
  64. **Mono**. Under **Mono**, click on **Editor**, and select your
  65. external editor of choice. Godot currently supports the following
  66. external editors:
  67. - Visual Studio 2019
  68. - Visual Studio Code
  69. - MonoDevelop
  70. - Visual Studio for Mac
  71. - JetBrains Rider
  72. See the following sections for how to configure an external editor:
  73. JetBrains Rider
  74. ~~~~~~~~~~~~~~~
  75. After reading the "Prerequisites" section, you can download and install
  76. `JetBrains Rider <https://www.jetbrains.com/rider/download>`__.
  77. In Godot's **Editor → Editor Settings** menu:
  78. - Set **Mono** -> **Editor** -> **External Editor** to **JetBrains Rider**.
  79. - Set **Mono** -> **Builds** -> **Build Tool** to **dotnet CLI**.
  80. In Rider:
  81. - Set **MSBuild version** to **.NET Core**.
  82. - Install the **Godot support** plugin.
  83. Visual Studio Code
  84. ~~~~~~~~~~~~~~~~~~
  85. After reading the "Prerequisites" section, you can download and install
  86. `Visual Studio Code <https://code.visualstudio.com/download>`__ (aka VS Code).
  87. In Godot's **Editor → Editor Settings** menu:
  88. - Set **Mono** -> **Editor** -> **External Editor** to **Visual Studio Code**.
  89. - Set **Mono** -> **Builds** -> **Build Tool** to **dotnet CLI**.
  90. In Visual Studio Code:
  91. - Install the `C# <https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp>`__ extension.
  92. - Install the `Mono Debug <https://marketplace.visualstudio.com/items?itemName=ms-vscode.mono-debug>`__ extension.
  93. - Install the `C# Tools for Godot <https://marketplace.visualstudio.com/items?itemName=neikeq.godot-csharp-vscode>`__ extension.
  94. .. note:: If you are using Linux you need to install the
  95. `Mono SDK <https://www.mono-project.com/download/stable/#download-lin>`__
  96. for the C# tools plugin to work.
  97. To configure a project for debugging open the Godot project folder in VS Code.
  98. Go to the Run tab and click on **Add Configuration...**. Select **C# Godot**
  99. from the dropdown menu. Open the ``tasks.json`` and ``launch.json`` files that
  100. were created. Change the executable setting in ``launch.json`` and command
  101. settings in ``tasks.json`` to your Godot executable path. Now, when you start
  102. the debugger in VS Code, your Godot project will run.
  103. Visual Studio (Windows only)
  104. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  105. Download and install the latest version of
  106. `Visual Studio <https://visualstudio.microsoft.com/downloads/>`__.
  107. Visual Studio will include the required SDKs if you have the correct
  108. workloads selected, so you don't need to manually install the things
  109. listed in the "Prerequisites" section.
  110. While installing Visual Studio, select these workloads:
  111. - Mobile development with .NET
  112. - .NET Core cross-platform development
  113. In Godot's **Editor → Editor Settings** menu:
  114. - Set **Mono** -> **Editor** -> **External Editor** to **Visual Studio**.
  115. - Set **Mono** -> **Builds** -> **Build Tool** to **dotnet CLI**.
  116. Next, you need to download the Godot Visual Studio extension from github
  117. `here <https://github.com/godotengine/godot-csharp-visualstudio/releases>`__.
  118. Double click on the downloaded file and follow the installation process.
  119. Creating a C# script
  120. --------------------
  121. After you successfully set up C# for Godot, you should see the following option
  122. when selecting **Attach Script** in the context menu of a node in your scene:
  123. .. image:: img/attachcsharpscript.png
  124. Note that while some specifics change, most concepts work the same
  125. when using C# for scripting. If you're new to Godot, you may want to follow
  126. the tutorials on :ref:`doc_scripting` at this point.
  127. While some places in the documentation still lack C# examples, most concepts
  128. can be transferred easily from GDScript.
  129. Project setup and workflow
  130. --------------------------
  131. When you create the first C# script, Godot initializes the C# project files
  132. for your Godot project. This includes generating a C# solution (``.sln``)
  133. and a project file (``.csproj``), as well as some utility files and folders
  134. (``.mono`` and ``Properties/AssemblyInfo.cs``).
  135. All of these but ``.mono`` are important and should be committed to your
  136. version control system. ``.mono`` can be safely added to the ignore list of your VCS.
  137. When troubleshooting, it can sometimes help to delete the ``.mono`` folder
  138. and let it regenerate.
  139. Example
  140. -------
  141. Here's a blank C# script with some comments to demonstrate how it works.
  142. .. code-block:: csharp
  143. using Godot;
  144. using System;
  145. public class YourCustomClass : Node
  146. {
  147. // Member variables here, example:
  148. private int a = 2;
  149. private string b = "textvar";
  150. public override void _Ready()
  151. {
  152. // Called every time the node is added to the scene.
  153. // Initialization here.
  154. GD.Print("Hello from C# to Godot :)");
  155. }
  156. public override void _Process(float delta)
  157. {
  158. // Called every frame. Delta is time since the last frame.
  159. // Update game logic here.
  160. }
  161. }
  162. As you can see, functions normally in global scope in GDScript like Godot's
  163. ``print`` function are available in the ``GD`` class which is part of
  164. the ``Godot`` namespace. For a list of methods in the ``GD`` class, see the
  165. class reference pages for
  166. :ref:`@GDScript <class_@gdscript>` and :ref:`@GlobalScope <class_@globalscope>`.
  167. .. note::
  168. Keep in mind that the class you wish to attach to your node should have the same
  169. name as the ``.cs`` file. Otherwise, you will get the following error
  170. and won't be able to run the scene:
  171. *"Cannot find class XXX for script res://XXX.cs"*
  172. General differences between C# and GDScript
  173. -------------------------------------------
  174. The C# API uses ``PascalCase`` instead of ``snake_case`` in GDScript/C++.
  175. Where possible, fields and getters/setters have been converted to properties.
  176. In general, the C# Godot API strives to be as idiomatic as is reasonably possible.
  177. For more information, see the :ref:`doc_c_sharp_differences` page.
  178. .. warning::
  179. You need to (re)build the project assemblies whenever you want to see new
  180. exported variables or signals in the editor. This build can be manually
  181. triggered by clicking the word **Build** in the top right corner of the
  182. editor. You can also click **Mono** at the bottom of the editor window
  183. to reveal the Mono panel, then click the **Build Project** button.
  184. You will also need to rebuild the project assemblies to apply changes in
  185. "tool" scripts.
  186. Current gotchas and known issues
  187. --------------------------------
  188. As C# support is quite new in Godot, there are some growing pains and things
  189. that need to be ironed out. Below is a list of the most important issues
  190. you should be aware of when diving into C# in Godot, but if in doubt, also
  191. take a look over the official
  192. `issue tracker for Mono issues <https://github.com/godotengine/godot/labels/topic%3Amono>`_.
  193. - Writing editor plugins is possible, but it is currently quite convoluted.
  194. - State is currently not saved and restored when hot-reloading,
  195. with the exception of exported variables.
  196. - Attached C# scripts should refer to a class that has a class name
  197. that matches the file name.
  198. - There are some methods such as ``Get()``/``Set()``, ``Call()``/``CallDeferred()``
  199. and signal connection method ``Connect()`` that rely on Godot's ``snake_case`` API
  200. naming conventions.
  201. So when using e.g. ``CallDeferred("AddChild")``, ``AddChild`` will not work because
  202. the API is expecting the original ``snake_case`` version ``add_child``. However, you
  203. can use any custom properties or methods without this limitation.
  204. As of Godot 3.2.2, exporting Mono projects is supported for desktop platforms
  205. (Linux, Windows and macOS), Android, HTML5, and iOS. The only platform not
  206. supported yet is UWP.
  207. Performance of C# in Godot
  208. --------------------------
  209. According to some preliminary `benchmarks <https://github.com/cart/godot3-bunnymark>`_,
  210. the performance of C# in Godot — while generally in the same order of magnitude
  211. — is roughly **~4×** that of GDScript in some naive cases. C++ is still
  212. a little faster; the specifics are going to vary according to your use case.
  213. GDScript is likely fast enough for most general scripting workloads.
  214. C# is faster, but requires some expensive marshalling when talking to Godot.
  215. Using NuGet packages in Godot
  216. -----------------------------
  217. `NuGet <https://www.nuget.org/>`_ packages can be installed and used with Godot,
  218. as with any C# project. Many IDEs are able to add packages directly.
  219. They can also be added manually by adding the package reference in
  220. the ``.csproj`` file located in the project root:
  221. .. code-block:: xml
  222. :emphasize-lines: 2
  223. <ItemGroup>
  224. <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
  225. </ItemGroup>
  226. ...
  227. </Project>
  228. As of Godot 3.2.3, Godot automatically downloads and sets up newly added NuGet
  229. packages the next time it builds the project.
  230. Profiling your C# code
  231. ----------------------
  232. - `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.
  233. - External Mono profiler like `JetBrains dotTrace <https://www.jetbrains.com/profiler/>`_ can be used as described `here <https://github.com/godotengine/godot/pull/34382>`_.