c_sharp_basics.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 5.x .NET framework, including full support
  19. for C# 7.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. While Godot has its own script editor, its support for C# is kept
  64. minimal; it's recommended that you use an external IDE or editor
  65. instead, such as `Visual Studio Code <https://code.visualstudio.com/>`_
  66. or MonoDevelop. These provide auto-completion, debugging and other features
  67. useful when working with C#. To set it up in Godot, click on
  68. **Editor → Editor Settings** and scroll down to the bottom to the
  69. **Mono** settings. Under **Mono**, click on **Editor** then choose
  70. your external editor of choice.
  71. .. note:: If you are using Visual Studio Code, ensure you download and install
  72. the `C# extension <https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp>`_
  73. to enable features like syntax highlighting and IntelliSense.
  74. Creating a C# script
  75. --------------------
  76. After you successfully set up C# for Godot, you should see the following option
  77. when selecting ``Attach script`` in the context menu of a node in your scene:
  78. .. image:: img/attachcsharpscript.png
  79. Note that while some specifics change, most concepts work the same
  80. when using C# for scripting. If you're new to Godot, you may want to follow
  81. the tutorials on :ref:`doc_scripting` at this point.
  82. While some places in the documentation still lack C# examples, most concepts
  83. can be transferred easily from GDScript.
  84. Project setup and workflow
  85. --------------------------
  86. When you create the first C# script, Godot initializes the C# project files
  87. for your Godot project. This includes generating a C# solution (``.sln``)
  88. and a project file (``.csproj``), as well as some utility files and folders
  89. (``.mono`` and ``Properties/AssemblyInfo.cs``).
  90. All of these but ``.mono`` are important and should be committed to your
  91. version control system. ``.mono`` can be safely added to the ignore list of your VCS.
  92. When troubleshooting, it can sometimes help to delete the ``.mono`` folder
  93. and let it regenerate.
  94. Note that currently, there are some issues where Godot and the C# project
  95. don't stay in sync; if you delete, rename or move a C# script, the change
  96. may not be reflected in the C# project file.
  97. In cases like this, you will have to edit the C# project file manually.
  98. For example, if you created a script (e.g. ``Test.cs``) and delete it in Godot,
  99. compilation will fail because the missing file is still expected to be there
  100. by the C# project file. For now, you can simply open up the ``.csproj`` file
  101. and look for the ``ItemGroup``, there should be a line included
  102. like the following:
  103. .. code-block:: xml
  104. :emphasize-lines: 2
  105. <ItemGroup>
  106. <Compile Include="Test.cs" />
  107. <Compile Include="AnotherTest.cs" />
  108. </ItemGroup>
  109. Simply remove that line and your project should build correctly again.
  110. Same for renaming and moving things, simply rename and move them
  111. in the project file if needed.
  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 be
  142. named 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. - As explained above, the C# project isn't always kept in sync automatically
  159. when things are deleted, renamed or moved in Godot
  160. (`#12917 <https://github.com/godotengine/godot/issues/12917>`_).
  161. - Writing editor plugins is possible, but it is currently quite convoluted.
  162. - State is currently not saved and restored when hot-reloading,
  163. with the exception of exported variables.
  164. - Exporting Mono projects is only supported for desktop platforms
  165. (Linux, Windows and macOS). Android, iOS, HTML5 and UWP are not currently supported
  166. (`#20267 <https://github.com/godotengine/godot/issues/20267>`_,
  167. `#20268 <https://github.com/godotengine/godot/issues/20268>`_
  168. `#20270 <https://github.com/godotengine/godot/issues/20270>`_
  169. `#20271 <https://github.com/godotengine/godot/issues/20271>`_).
  170. - Attached C# scripts should refer to a class that has a class name
  171. that matches the file name.
  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" Version="11.0.2"/>
  190. </ItemGroup>
  191. ...
  192. </Project>
  193. Whenever packages are added or modified, run ``nuget restore`` in the root of the
  194. project directory. To ensure that NuGet packages will be available for
  195. msbuild to use, run:
  196. .. code-block:: none
  197. msbuild /t:restore