c_sharp_basics.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 Code
  72. - MonoDevelop
  73. - Visual Studio for Mac
  74. - JetBrains Rider
  75. .. note:: If you are using Visual Studio Code, ensure you download and install
  76. the `C# extension <https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp>`_
  77. to enable features like syntax highlighting and IntelliSense.
  78. Creating a C# script
  79. --------------------
  80. After you successfully set up C# for Godot, you should see the following option
  81. when selecting ``Attach script`` in the context menu of a node in your scene:
  82. .. image:: img/attachcsharpscript.png
  83. Note that while some specifics change, most concepts work the same
  84. when using C# for scripting. If you're new to Godot, you may want to follow
  85. the tutorials on :ref:`doc_scripting` at this point.
  86. While some places in the documentation still lack C# examples, most concepts
  87. can be transferred easily from GDScript.
  88. Project setup and workflow
  89. --------------------------
  90. When you create the first C# script, Godot initializes the C# project files
  91. for your Godot project. This includes generating a C# solution (``.sln``)
  92. and a project file (``.csproj``), as well as some utility files and folders
  93. (``.mono`` and ``Properties/AssemblyInfo.cs``).
  94. All of these but ``.mono`` are important and should be committed to your
  95. version control system. ``.mono`` can be safely added to the ignore list of your VCS.
  96. When troubleshooting, it can sometimes help to delete the ``.mono`` folder
  97. and let it regenerate.
  98. Note that currently, there are some issues where Godot and the C# project
  99. don't stay in sync; if you delete, rename or move a C# script, the change
  100. may not be reflected in the C# project file.
  101. In cases like this, you will have to edit the C# project file manually.
  102. For example, if you created a script (e.g. ``Test.cs``) and delete it in Godot,
  103. compilation will fail because the missing file is still expected to be there
  104. by the C# project file. For now, you can simply open up the ``.csproj`` file
  105. and look for the ``ItemGroup``, there should be a line included
  106. like the following:
  107. .. code-block:: xml
  108. :emphasize-lines: 2
  109. <ItemGroup>
  110. <Compile Include="Test.cs" />
  111. <Compile Include="AnotherTest.cs" />
  112. </ItemGroup>
  113. Simply remove that line and your project should build correctly again.
  114. Same for renaming and moving things, simply rename and move them
  115. in the project file if needed.
  116. Example
  117. -------
  118. Here's a blank C# script with some comments to demonstrate how it works.
  119. .. code-block:: csharp
  120. using Godot;
  121. using System;
  122. public class YourCustomClass : Node
  123. {
  124. // Member variables here, example:
  125. private int a = 2;
  126. private string b = "textvar";
  127. public override void _Ready()
  128. {
  129. // Called every time the node is added to the scene.
  130. // Initialization here.
  131. GD.Print("Hello from C# to Godot :)");
  132. }
  133. public override void _Process(float delta)
  134. {
  135. // Called every frame. Delta is time since the last frame.
  136. // Update game logic here.
  137. }
  138. }
  139. As you can see, functions normally in global scope in GDScript like Godot's
  140. ``print`` function are available in the ``GD`` class which is part of
  141. the ``Godot`` namespace. For a list of methods in the ``GD`` class, see the
  142. class reference pages for
  143. :ref:`@GDScript <class_@gdscript>` and :ref:`@GlobalScope <class_@globalscope>`.
  144. .. note::
  145. Keep in mind that the class you wish to attach to your node should have the same
  146. name as the ``.cs`` file. Otherwise, you will get the following error
  147. and won't be able to run the scene:
  148. *"Cannot find class XXX for script res://XXX.cs"*
  149. General differences between C# and GDScript
  150. -------------------------------------------
  151. The C# API uses ``PascalCase`` instead of ``snake_case`` in GDScript/C++.
  152. Where possible, fields and getters/setters have been converted to properties.
  153. In general, the C# Godot API strives to be as idiomatic as is reasonably possible.
  154. For more information, see the :ref:`doc_c_sharp_differences` page.
  155. Current gotchas and known issues
  156. --------------------------------
  157. As C# support is quite new in Godot, there are some growing pains and things
  158. that need to be ironed out. Below is a list of the most important issues
  159. you should be aware of when diving into C# in Godot, but if in doubt, also
  160. take a look over the official
  161. `issue tracker for Mono issues <https://github.com/godotengine/godot/labels/topic%3Amono>`_.
  162. - As explained above, the C# project isn't always kept in sync automatically
  163. when things are deleted, renamed or moved in Godot
  164. (`#12917 <https://github.com/godotengine/godot/issues/12917>`_).
  165. - Writing editor plugins is possible, but it is currently quite convoluted.
  166. - State is currently not saved and restored when hot-reloading,
  167. with the exception of exported variables.
  168. - Exporting Mono projects is only supported for desktop platforms
  169. (Linux, Windows and macOS). Android, iOS, HTML5 and UWP are not currently supported
  170. (`#20267 <https://github.com/godotengine/godot/issues/20267>`_,
  171. `#20268 <https://github.com/godotengine/godot/issues/20268>`_
  172. `#20270 <https://github.com/godotengine/godot/issues/20270>`_
  173. `#20271 <https://github.com/godotengine/godot/issues/20271>`_).
  174. - Attached C# scripts should refer to a class that has a class name
  175. that matches the file name.
  176. - There are some methods such as ``Get()``/``Set()``, ``Call()``/``CallDeferred()``
  177. and signal connection method ``Connect()`` that rely on Godot's ``snake_case`` API
  178. naming conventions.
  179. So when using e.g. ``CallDeferred("AddChild")``, ``AddChild`` will not work because
  180. the API is expecting the original ``snake_case`` version ``add_child``. However, you
  181. can use any custom properties or methods without this limitation.
  182. Performance of C# in Godot
  183. --------------------------
  184. According to some preliminary `benchmarks <https://github.com/cart/godot3-bunnymark>`_,
  185. the performance of C# in Godot — while generally in the same order of magnitude
  186. — is roughly **~4×** that of GDScript in some naive cases. C++ is still
  187. a little faster; the specifics are going to vary according to your use case.
  188. GDScript is likely fast enough for most general scripting workloads.
  189. C# is faster, but requires some expensive marshalling when talking to Godot.
  190. Using NuGet packages in Godot
  191. -----------------------------
  192. `NuGet <https://www.nuget.org/>`_ packages can be installed and used with Godot,
  193. as with any C# project. Many IDEs are able to add packages directly.
  194. They can also be added manually by adding the package reference in
  195. the ``.csproj`` file located in the project root:
  196. .. code-block:: xml
  197. :emphasize-lines: 2
  198. <ItemGroup>
  199. <PackageReference Include="Newtonsoft.Json" Version="11.0.2"/>
  200. </ItemGroup>
  201. ...
  202. </Project>
  203. Whenever packages are added or modified, run ``nuget restore`` in the root of the
  204. project directory. To ensure that NuGet packages will be available for
  205. msbuild to use, run:
  206. .. code-block:: none
  207. msbuild /t:restore
  208. Profiling your C# code
  209. -----------------------------
  210. - `Mono log profiler <https://www.mono-project.com/docs/debug+profile/profile/profiler/>`_ is available via `this PR <https://github.com/godotengine/godot/pull/26513>`_
  211. - External Mono profiler like `JetBrains dotTrace <https://www.jetbrains.com/profiler/>`_ can be used as described `here <https://github.com/godotengine/godot/pull/34382>`_.