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