2
0

c_sharp_basics.rst 14 KB

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