c_sharp_basics.rst 13 KB

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