C# basics¶
Introdução¶
Aviso
Suporte a C# é um novo recurso no Godot 3.0. Por isso, você ainda pode se deparar com alguns problemas ou encontrar lugares onde a documentação poderia ser melhorada. Por favor relate problemas com C# no Godot na página do motor no Github, e qualquer problema de documentação na página da documentação no Github.
This page provides a brief introduction to C#, both what it is and how to use it in Godot. Afterwards, you may want to look at how to use specific features, read about the differences between the C# and the GDScript API and (re)visit the Scripting section of the step-by-step tutorial.
C# is a high-level programming language developed by Microsoft. In Godot, it is implemented with the Mono 6.x .NET framework, including full support for C# 8.0. Mono is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime. A good starting point for checking its capabilities is the Compatibility page in the Mono documentation.
Nota
Esse não é um tutorial completo e abrangente sobre a linguagem C#. Se você ainda não estiver familiarizado com sua sintaxe ou recursos, consulte o guia C# da Microsoft ou procure uma introdução adequada em outro lugar.
Setting up C# for Godot¶
Windows (Visual Studio)¶
Download and install the latest version of Visual Studio (not Visual Studio Code), which contains utilities required to use C# in Godot. If you don't plan on using the Visual Studio IDE, you can download just the Visual Studio Build Tools instead. 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.
Windows (JetBrains Rider)¶
JetBrains Rider comes with bundled MSBuild, so nothing extra is required. Make sure to set the following preferences:
In Godot's Editor Settings:
- Set Mono External Editor to JetBrains Rider.
- set Mono Build Tool to JetBrains Mono.
In Rider:
- Set MSBuild version to either Bundled with Rider or .NET Core.
- Install the Godot support plugin.
macOS e Linux¶
Baixe e instale a última versão do Mono SDK.
Nota
To download Mono on macOS, use the "Stable Channel" link from the Mono Downloads Page. The Visual Studio channel is an earlier version of Mono and will not work.
Additional notes¶
Your Godot version must have Mono support enabled, so make sure to download the Mono version of Godot. If you are building Godot from source, make sure to follow the steps to enable Mono support in your build as outlined in the Compiling with Mono page.
In summary, you must have installed Visual Studio or Mono (depending on your operating system) and the Mono-enabled version of Godot.
Configurando um editor externo¶
O suporte de C# direto no editor de scripts do Godot é minimo. Considere usar uma IDE ou editor externos, como por exemplo Visual Studio Code ou MonoDevelop. Estes editores possuem auto completar, ferramentas de depuração e outras funcionalidades úteis para o desenvolvimento em C#. Para selecionar um editor externo no Godot, clique em Editor -> Editor Settings e role a página até o Mono. Em Mono, clique em Editor então selecione o editor de sua preferência. Godot atualmente dá suporte aos seguintes editores externos:
- Visual Studio 2019
- Visual Studio Code
- MonoDevelop
- Visual Studio for Mac
- JetBrains Rider
Nota
Se você está usando Visual Studio Code, baixe e instale a extensão de C# para permitir recursos como marcação de sintaxe e IntelliSense.
Nota
If you are using Visual Studio 2019, you must follow the instructions found in the :ref:doc_c_sharp_configuring_vs_2019_for_debugging section below.
Criando um script C#¶
After you successfully set up C# for Godot, you should see the following option when selecting Attach Script in the context menu of a node in your scene:

Note that while some specifics change, most concepts work the same when using C# for scripting. If you're new to Godot, you may want to follow the tutorials on Scripting at this point. While some places in the documentation still lack C# examples, most concepts can be transferred easily from GDScript.
Configuração de projeto e fluxo de trabalho¶
When you create the first C# script, Godot initializes the C# project files
for your Godot project. This includes generating a C# solution (.sln
)
and a project file (.csproj
), as well as some utility files and folders
(.mono
and Properties/AssemblyInfo.cs
).
All of these but .mono
are important and should be committed to your
version control system. .mono
can be safely added to the ignore list of your VCS.
When troubleshooting, it can sometimes help to delete the .mono
folder
and let it regenerate.
Exemplo¶
Aqui está um script C# em branco com alguns comentários para demonstrar como funciona.
using Godot;
using System;
public class YourCustomClass : Node
{
// Member variables here, example:
private int a = 2;
private string b = "textvar";
public override void _Ready()
{
// Called every time the node is added to the scene.
// Initialization here.
GD.Print("Hello from C# to Godot :)");
}
public override void _Process(float delta)
{
// Called every frame. Delta is time since the last frame.
// Update game logic here.
}
}
As you can see, functions normally in global scope in GDScript like Godot's
print
function are available in the GD
class which is part of
the Godot
namespace. For a list of methods in the GD
class, see the
class reference pages for
@GDScript and @GlobalScope.
Nota
Tenha em mente que a classe que você deseja anexar ao seu nó deve ser nomeada como um arquivo .cs
. Caso contrário, você receberá o seguinte erro e não poderá executar a cena: "Não é possível encontrar a classe XXX para o script res:// XXX.cs"
Diferenças gerais entre o C# e o GDScript¶
A API do C# usa o PascalCase
em vez do snake_case
no GDScript/C++. Sempre que possível, fields e getters/setters foram convertidos em propriedades. Em geral, a API C# Godot se esforça para ser tão idiomática quanto for razoavelmente possível.
For more information, see the C# API differences to GDScript page.
Aviso
You need to (re)build the project assemblies whenever you want to see new exported variables or signals in the editor. This build can be manually triggered by clicking the word Mono at the bottom of the editor window to reveal the Mono panel, then clicking the Build Project button.
You will also need to rebuild the project assemblies to apply changes in "tool" scripts.
Pegadinhas gerais e problemas conhecidos¶
As C# support is quite new in Godot, there are some growing pains and things that need to be ironed out. Below is a list of the most important issues you should be aware of when diving into C# in Godot, but if in doubt, also take a look over the official issue tracker for Mono issues.
- Escrever plugins para o editor é possível, mas atualmente é bastante complicado.
- Atualmente o estado não é salvo e restaurado durante o "hot-reloading", com exceção das variáveis exportadas.
- Os scripts C # anexados devem se referir a uma classe que tenha um nome de classe que corresponda ao nome do arquivo.
- Existem alguns métodos como
Get()
/Set()
,Call()
/CallDeferred()
e método de conexão de sinalConnect()
que dependem dos padrões de nomeação da APIsnake_case
de Godot. Então, por exemplo ao usarCallDeferred("AddChild")
,AddChild
não vai funcionar porque a API está esperando a chamada no formatosnake_case
comoadd_child
. No entanto, você pode usar quaisquer propriedades ou métodos personalizados sem essa limitação.
As of Godot 3.2.2, exporting Mono projects is supported for desktop platforms (Linux, Windows and macOS), Android, HTML5, and iOS. The only platform not supported yet is UWP.
Performance do C# no Godot¶
According to some preliminary benchmarks, the performance of C# in Godot — while generally in the same order of magnitude — is roughly ~4× that of GDScript in some naive cases. C++ is still a little faster; the specifics are going to vary according to your use case. GDScript is likely fast enough for most general scripting workloads. C# is faster, but requires some expensive marshalling when talking to Godot.
Using NuGet packages in Godot¶
NuGet packages can be installed and used with Godot,
as with any C# project. Many IDEs are able to add packages directly.
They can also be added manually by adding the package reference in
the .csproj
file located in the project root:
<ItemGroup>
<PackageReference Include="Newtonsoft.Json">
<Version>11.0.2</Version>
</PackageReference>
</ItemGroup>
...
</Project>
Nota
Por padrão, ferramentas como NuGet colocam Version`
como atributo do Nó PackageReference`
. Você deve criar manualmente um nó de Versão como mostrado acima. Isto é porque a versão utilizada do MSBuild requer isto. (Isto será corrigido no Godot 4.0)
Whenever packages are added or modified, run nuget restore
(not dotnet restore
) in the root of the
project directory. To ensure that NuGet packages will be available for
msbuild to use, run:
msbuild /t:restore
Perfilando seu código C#¶
- Mono log profiler is available for Linux and macOS. Due to a Mono change, it does not work on Windows currently.
- Profiler de Mono Externo como JetBrains dotTrace pode ser usado como descrito aqui.
Configuração VS 2019 para depuração¶
Nota
Godot tem suporte integrado para fluxos de trabalho envolvendo várias IDEs populares de C#. O suporte nativo para o Visual Studio será incluso em versões futuras, mas enquanto isso, os passos abaixo podem permitir que você configure o Visual Studio 2019 para utilização dos projetos de Godot em C#.
- Instale o Visual Studio 2019 com os componentes
.NET desktop development
eDesktop development with C++
selecionados. - Certifique-se de não ter Xamarin instalado. Não escolha a opção
Mobile development with .NET
. Xamarin altera as DLLs usadas pelo MonoDebugger, que quebra a depuração. - Instale a extensão ``VSMonoDebugger <https://marketplace.visualstudio.com/items?itemName=GordianDotNet.VSMonoDebugger0d62>`_.
- No VS 2019 --> Extensions --> Mono ->Settings:
- Selecione
Debug/Deploy to local Windows
. - Deixe
Local Deploy Path
em branco. - Defina a porta de depuração em
Mono Debug Port
para a porta definida em Godot --> Projeto --> Configurações de projeto --> Mono --> Agente depurador. - Selecione também
Wait for Debugger
nas opções do Mono dentro do Godot. Este Godot Addon pode ser útil.
- Selecione
- Execute o jogo no Godot. A tela de inicialização do Godot será apresentada enquanto espera que seu depurador se conecte.
- No VS 2019, abra seu projeto e escolha Extensions --> Mono --> Attach to Mono Debugger.
Configuring Visual Studio Code for debugging¶
To configure debugging, open Visual Studio Code and download the Mono Debug extension from Microsoft and the Godot extension by Ignacio. Then open the Godot project folder in VS Code. Go to the Run tab and click on create a launch.json file. Select C# Godot from the dropdown menu. Now, when you start the debugger in VS Code your Godot project will run.