c_sharp_basics.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. Setting up C# for Godot
  32. -----------------------
  33. Windows (Visual Studio)
  34. ~~~~~~~~~~~~~~~~~~~~~~~
  35. Download and install the latest version of
  36. `Visual Studio <https://visualstudio.microsoft.com/downloads/>`_
  37. (*not* Visual Studio Code), which contains utilities required to use
  38. C# in Godot. If you don't plan on using the Visual Studio IDE,
  39. you can download just the
  40. `Visual Studio Build Tools <https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools&rel=15>`_
  41. instead.
  42. Make sure you at least have the .NET Framework 4.5 targeting pack installed, you can get it using any of the installers mentioned above inside the "Individual components" tab.
  43. Windows (JetBrains Rider)
  44. ~~~~~~~~~~~~~~~~~~~~~~~~~
  45. JetBrains Rider comes with bundled MSBuild, so nothing extra is required.
  46. Make sure to set the following preferences:
  47. - In Godot:
  48. - Mono External Editor to JetBrains Rider
  49. - Mono Build Tool to JetBrains Mono.
  50. - In Rider:
  51. - Set ``MSBuild version`` to either bundled with Rider or .NET Core.
  52. - Install **Godot support** plugin.
  53. macOS and Linux
  54. ~~~~~~~~~~~~~~~
  55. Download and install the latest version of the
  56. `Mono SDK <http://www.mono-project.com/download/>`_. As of Godot 3.1 beta 3,
  57. the version number doesn't matter since Godot bundles its own Mono 5.18
  58. installation. We only need the Mono installation for NuGet and MSBuild
  59. which are required to use C# in Godot.
  60. .. note:: To download Mono on macOS, use the "Stable Channel" link
  61. from the `Mono Downloads Page <http://www.mono-project.com/download/>`_.
  62. The Visual Studio channel is an earlier version of Mono and
  63. will not work.
  64. Additional notes
  65. ~~~~~~~~~~~~~~~~
  66. Your Godot version must have Mono support enabled,
  67. so make sure to download the **Mono version** of Godot.
  68. If you are building Godot from source, make sure to follow the steps to
  69. enable Mono support in your build as outlined in the
  70. :ref:`doc_compiling_with_mono` page.
  71. In summary, you must have installed Visual Studio or Mono (depending
  72. on your operating system) **and** the Mono-enabled version of Godot.
  73. Configuring an external editor
  74. ------------------------------
  75. C# support in Godot's script editor is minimal. Consider using an
  76. external IDE or editor, such as `Visual Studio Code <https://code.visualstudio.com/>`_
  77. or MonoDevelop. These provide autocompletion, debugging, and other
  78. useful features for C#. To select an external editor in Godot,
  79. click on **Editor → Editor Settings** and scroll down to
  80. **Mono**. Under **Mono**, click on **Editor**, and select your
  81. external editor of choice. Godot currently supports the following
  82. external editors:
  83. - Visual Studio 2019
  84. - Visual Studio Code
  85. - MonoDevelop
  86. - Visual Studio for Mac
  87. - JetBrains Rider
  88. .. note:: If you are using Visual Studio Code, ensure you download and install
  89. the `C# extension <https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp>`_
  90. to enable features like syntax highlighting and IntelliSense.
  91. .. note:: If you are using Visual Studio 2019, you must follow the instructions found in the "Configure VS2019 for Debugging" section below.
  92. Creating a C# script
  93. --------------------
  94. After you successfully set up C# for Godot, you should see the following option
  95. when selecting ``Attach script`` in the context menu of a node in your scene:
  96. .. image:: img/attachcsharpscript.png
  97. Note that while some specifics change, most concepts work the same
  98. when using C# for scripting. If you're new to Godot, you may want to follow
  99. the tutorials on :ref:`doc_scripting` at this point.
  100. While some places in the documentation still lack C# examples, most concepts
  101. can be transferred easily from GDScript.
  102. Project setup and workflow
  103. --------------------------
  104. When you create the first C# script, Godot initializes the C# project files
  105. for your Godot project. This includes generating a C# solution (``.sln``)
  106. and a project file (``.csproj``), as well as some utility files and folders
  107. (``.mono`` and ``Properties/AssemblyInfo.cs``).
  108. All of these but ``.mono`` are important and should be committed to your
  109. version control system. ``.mono`` can be safely added to the ignore list of your VCS.
  110. When troubleshooting, it can sometimes help to delete the ``.mono`` folder
  111. and let it regenerate.
  112. Example
  113. -------
  114. Here's a blank C# script with some comments to demonstrate how it works.
  115. .. code-block:: csharp
  116. using Godot;
  117. using System;
  118. public class YourCustomClass : Node
  119. {
  120. // Member variables here, example:
  121. private int a = 2;
  122. private string b = "textvar";
  123. public override void _Ready()
  124. {
  125. // Called every time the node is added to the scene.
  126. // Initialization here.
  127. GD.Print("Hello from C# to Godot :)");
  128. }
  129. public override void _Process(float delta)
  130. {
  131. // Called every frame. Delta is time since the last frame.
  132. // Update game logic here.
  133. }
  134. }
  135. As you can see, functions normally in global scope in GDScript like Godot's
  136. ``print`` function are available in the ``GD`` class which is part of
  137. the ``Godot`` namespace. For a list of methods in the ``GD`` class, see the
  138. class reference pages for
  139. :ref:`@GDScript <class_@gdscript>` and :ref:`@GlobalScope <class_@globalscope>`.
  140. .. note::
  141. Keep in mind that the class you wish to attach to your node should have the same
  142. name as the ``.cs`` file. Otherwise, you will get the following error
  143. and won't be able to run the scene:
  144. *"Cannot find class XXX for script res://XXX.cs"*
  145. General differences between C# and GDScript
  146. -------------------------------------------
  147. The C# API uses ``PascalCase`` instead of ``snake_case`` in GDScript/C++.
  148. Where possible, fields and getters/setters have been converted to properties.
  149. In general, the C# Godot API strives to be as idiomatic as is reasonably possible.
  150. For more information, see the :ref:`doc_c_sharp_differences` page.
  151. Current gotchas and known issues
  152. --------------------------------
  153. As C# support is quite new in Godot, there are some growing pains and things
  154. that need to be ironed out. Below is a list of the most important issues
  155. you should be aware of when diving into C# in Godot, but if in doubt, also
  156. take a look over the official
  157. `issue tracker for Mono issues <https://github.com/godotengine/godot/labels/topic%3Amono>`_.
  158. - Writing editor plugins is possible, but it is currently quite convoluted.
  159. - State is currently not saved and restored when hot-reloading,
  160. with the exception of exported variables.
  161. - Attached C# scripts should refer to a class that has a class name
  162. that matches the file name.
  163. - There are some methods such as ``Get()``/``Set()``, ``Call()``/``CallDeferred()``
  164. and signal connection method ``Connect()`` that rely on Godot's ``snake_case`` API
  165. naming conventions.
  166. So when using e.g. ``CallDeferred("AddChild")``, ``AddChild`` will not work because
  167. the API is expecting the original ``snake_case`` version ``add_child``. However, you
  168. can use any custom properties or methods without this limitation.
  169. As of Godot 3.2.2, exporting Mono projects is supported for desktop platforms
  170. (Linux, Windows and macOS), Android, HTML5, and iOS. The only platform not
  171. supported yet is UWP.
  172. Performance of C# in Godot
  173. --------------------------
  174. According to some preliminary `benchmarks <https://github.com/cart/godot3-bunnymark>`_,
  175. the performance of C# in Godot — while generally in the same order of magnitude
  176. — is roughly **~4×** that of GDScript in some naive cases. C++ is still
  177. a little faster; the specifics are going to vary according to your use case.
  178. GDScript is likely fast enough for most general scripting workloads.
  179. C# is faster, but requires some expensive marshalling when talking to Godot.
  180. Using NuGet packages in Godot
  181. -----------------------------
  182. `NuGet <https://www.nuget.org/>`_ packages can be installed and used with Godot,
  183. as with any C# project. Many IDEs are able to add packages directly.
  184. They can also be added manually by adding the package reference in
  185. the ``.csproj`` file located in the project root:
  186. .. code-block:: xml
  187. :emphasize-lines: 2
  188. <ItemGroup>
  189. <PackageReference Include="Newtonsoft.Json">
  190. <Version>11.0.2</Version>
  191. </PackageReference>
  192. </ItemGroup>
  193. ...
  194. </Project>
  195. .. note::
  196. By default, tools like NuGet put ``Version`` as an attribute of the ```PackageReference``` Node. **You must manually create a Version node as shown above.** This is because the version of MSBuild used requires this. (This will be fixed in Godot 4.0.)
  197. Whenever packages are added or modified, run ``nuget restore`` (*not* ``dotnet restore``) in the root of the
  198. project directory. To ensure that NuGet packages will be available for
  199. msbuild to use, run:
  200. .. code-block:: none
  201. msbuild /t:restore
  202. Profiling your C# code
  203. ----------------------
  204. - `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.
  205. - External Mono profiler like `JetBrains dotTrace <https://www.jetbrains.com/profiler/>`_ can be used as described `here <https://github.com/godotengine/godot/pull/34382>`_.
  206. Configuring VS 2019 for debugging
  207. ---------------------------------
  208. .. note::
  209. Godot has built-in support for workflows involving several popular C# IDEs.
  210. Built-in support for Visual Studio will be including in future versions,
  211. but in the meantime, the steps below can let you configure VS 2019 for use
  212. with Godot C# projects.
  213. 1. Install VS 2019 with ``.NET desktop development`` and ``Desktop development with C++`` workloads selected.
  214. 2. **Ensure that you do not have Xamarin installed.** Do not choose the ``Mobile development with .NET`` workload. Xamarin changes the DLLs used by MonoDebugger, which breaks debugging.
  215. 3. Install the `VSMonoDebugger extension <https://marketplace.visualstudio.com/items?itemName=GordianDotNet.VSMonoDebugger0d62>`_.
  216. 4. In VS 2019 --> Extensions --> Mono --> Settings:
  217. - Select ``Debug/Deploy to local Windows``.
  218. - Leave ``Local Deploy Path`` blank.
  219. - Set the ``Mono Debug Port`` to the port in Godot --> Project --> Project Settings --> Mono --> Debugger Agent.
  220. - Also select ``Wait for Debugger`` in the Godot Mono options. `This Godot Addon <https://godotengine.org/asset-library/asset/435>`_ may be helpful.
  221. 5. Run the game in Godot. It should hang at the Godot splash screen while it waits for your debugger to attach.
  222. 6. In VS 2019, open your project and choose Extensions --> Mono --> Attach to Mono Debugger.
  223. Configuring Visual Studio Code for debugging
  224. --------------------------------------------
  225. To configure Visual Studio Code for debugging open up a project in Godot. Click on Project
  226. and open the project settings. Scroll down and click on Debugger Agent under the Mono
  227. category. Then turn on the setting "wait for debugger." Next, copy the port number
  228. and open up Visual Studio Code.
  229. You need to download the Mono Debug extension from Microsoft. Then open the Godot
  230. project folder. Go to the run tab and click on create a launch.json file. Select C#
  231. Mono from the dropdown menu. When the launch.json file is automatically opened,
  232. change the port number to the number you copied previously and save the file. On the
  233. run tab, switch the run setting from launch to attach. Whenever you want to debug,
  234. make sure Wait for Debugger is turned on in Godot, run the project, and run the
  235. debugger in Visual Studio Code.