Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Conceptos básicos de C #

Introducción

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 .NET 6.0.

Atención

Projects written in C# using Godot 4 currently cannot be exported to the web platform. To use C# on the web platform, consider Godot 3 instead. Android and iOS platform support is available as of Godot 4.2, but is experimental and some limitations apply.

Nota

Este es no un tutorial a gran escala sobre el lenguaje C# en general. Si aún no está familiarizado con su sintaxis o características, consulte la guía Microsoft C# o busque una introducción adecuada en otro lugar.

Pre-requisitos

Godot bundles the parts of .NET needed to run already compiled games. However, Godot does not bundle the tools required to build and compile games, such as MSBuild and the C# compiler. These are included in the .NET SDK, and need to be installed separately.

In summary, you must have installed the .NET SDK and the .NET-enabled version of Godot.

Download and install the latest stable version of the SDK from the .NET download page.

Importante

Asegúrese de instalar la versión de 64 bits de los SDK si está utilizando la versión de 64 bits de Godot.

If you are building Godot from source, make sure to follow the steps to enable .NET support in your build as outlined in the Compiling with .NET page.

Configuración de un editor externo

C# support in Godot's built-in script editor is minimal. Consider using an external IDE or editor, such as Visual Studio Code or MonoDevelop. These provide autocompletion, debugging, and other useful features for C#. To select an external editor in Godot, click on Editor → Editor Settings and scroll down to Dotnet. Under Dotnet, click on Editor, and select your external editor of choice. Godot currently supports the following external editors:

  • Visual Studio 2022

  • Visual Studio Code

  • MonoDevelop

  • Visual Studio for Mac

  • JetBrains Rider

Consulte las siguientes secciones para saber cómo configurar un editor externo:

JetBrains Rider

Después de leer la sección "Requisitos previos", puede descargar e instalar JetBrains Rider <https://www.jetbrains.com/rider/download> __.

En el menú Editor → Configuración del editor de Godot:

  • Set Dotnet -> Editor -> External Editor to JetBrains Rider.

En Rider:

  • Establezca Vesión de MSBuild a .NET Core.

  • Instale el plugin de Godot support.

Visual Studio Code

Después de leer la sección "Requisitos previos", puede descargar e instalar Visual Studio Code <https://code.visualstudio.com/download> __ (también conocido como VS Code).

En el menú Editor → Configuración del editor de Godot:

  • Set Dotnet -> Editor -> External Editor to Visual Studio Code.

En Visual Studio Code:

  • Instala la extensión C#.

Nota

Si usas Linux necesitarás instalar Mono SDK <https://www.mono-project.com/download/stable/#download-lin> para que el plugin C# tools funcione.

To configure a project for debugging, you need a tasks.json and launch.json file in the .vscode folder with the necessary configuration. An example configuration can be found here . In the launch.json file, make sure the program parameter in the relevant configuration points to your Godot executable, either by changing it to the path of the executable or by defining a GODOT4 environment variable that points to the executable. Now, when you start the debugger in Visual Studio Code, your Godot project will run.

Visual Studio (Solo Windows)

Descargue e instale la última versión de Visual Studio <https://visualstudio.microsoft.com/downloads/> __. Visual Studio incluirá los SDK necesarios si ha seleccionado las cargas de trabajo correctas, por lo que no es necesario que instale manualmente las cosas que se enumeran en la sección "Requisitos previos".

While installing Visual Studio, select this workload:

  • .NET desktop development

En el menú Editor → Configuración del editor de Godot:

  • Set Dotnet -> Editor -> External Editor to Visual Studio.

Nota

Si ves un error como "Unable to find package Godot.NET.Sdk", es posible que la configuración de NuGet esté incorrecta y necesite ser corregida.

Una forma sencilla de corregir el archivo de configuración de NuGet es regenerándolo. En una ventana del explorador de archivos, ve a %AppData%\NuGet. Cambia el nombre o elimina el archivo NuGet.Config. Cuando vuelvas a construir tu proyecto de Godot, el archivo se creará automáticamente con los valores predeterminados.

Creando un script de C#

Después de configurar con éxito C# para Godot, debería ver la siguiente opción al seleccionar Añadir script en el menú contextual de un nodo en su escena:

../../../_images/attachcsharpscript.webp

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 Lenguaje de Scripting at this point. While some documentation pages still lack C# examples, most notions can be transferred from GDScript.

Ajustes del proyecto y flujo de trabajo

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 (.godot/mono). All of these but .godot/mono are important and should be committed to your version control system. Everything under .godot can be safely added to the ignore list of your VCS. When troubleshooting, it can sometimes help to delete the .godot/mono folder and let it regenerate.

Ejemplo

Aquí hay un script C# en blanco con algunos comentarios para demostrar cómo funciona.

using Godot;

public partial 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(double 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 static class which is part of the Godot namespace. For a full list of methods in the GD class, see the class reference pages for @GDScript and @GlobalScope.

Nota

Ten en cuenta que la clase que desees adjuntar a tu nodo debe ser nombrada igual que el archivo .cs. De lo contrario, se producirá el siguiente error:

"Cannot find class XXX for script res://XXX.cs"

Diferencias generales entre C# y GDScript

La API de C# usa PascalCase en lugar de snake_case en GDScript/C++. Siempre que ha sido posible, los campos y los getters/setters han sido convertidos a propiedades. En general, la API de C# Godot se esfuerza por ser fluida tanto como sea razonablemente posible.

Para más información, consulta la página Diferencias de la API de C# con GDScript.

Advertencia

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 Build button in the top right corner of the editor.

../../../_images/build_dotnet1.webp

También tendrás que reconstruir los ensamblajes del proyecto para aplicar los cambios en los scripts de las "herramientas".

Problemas actuales y problemas conocidos

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 .NET issues.

  • Es posible crear plugins para el editor, pero actualmente es bastante complicado.

  • Actualmente, el estado no se está guardando y se restaura durante la recarga en caliente, con la excepción de las variables exportadas.

  • Los scripts adjuntos de C# deben referirse a una clase que tenga el mismo nombre que el nombre del archivo. O lo que es lo mismo, el nombre de la clase que se declara en el script y el nombre del archivo deben ser igual.

  • There are some methods such as Get()/Set(), Call()/CallDeferred() and signal connection method Connect() that rely on Godot's snake_case API naming conventions. So when using e.g. CallDeferred("AddChild"), AddChild will not work because the API is expecting the original snake_case version add_child. However, you can use any custom properties or methods without this limitation. Prefer using the exposed StringName in the PropertyName, MethodName and SignalName to avoid extra StringName allocations and worrying about snake_case naming.

As of Godot 4.0, exporting .NET projects is supported for desktop platforms (Linux, Windows and macOS). Other platforms will gain support in future 4.x releases.

Common pitfalls

You might encounter the following error when trying to modify some values in Godot objects, e.g. when trying to change the X coordinate of a Node2D:

public partial class MyNode2D : Node2D
{
    public override _Ready()
    {
        Position.X = 100.0f;
        // CS1612: Cannot modify the return value of 'Node2D.Position' because
        // it is not a variable.
    }
}

This is perfectly normal. Structs (in this example, a Vector2) in C# are copied on assignment, meaning that when you retrieve such an object from a property or an indexer, you get a copy of it, not the object itself. Modifying said copy without reassigning it afterwards won't achieve anything.

The workaround is simple: retrieve the entire struct, modify the value you want to modify, and reassign the property.

var newPosition = Position;
newPosition.X = 100.0f;
Position = newPosition;

Since C# 10, it is also possible to use with expressions on structs, allowing you to do the same thing in a single line.

Position = Position with { X = 100.0f };

You can read more about this error on the C# language reference.

Rendimiento de C# en 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.

Most properties of Godot C# objects that are based on GodotObject (e.g. any Node like Control or Node3D like Camera3D) require native (interop) calls as they talk to Godot's C++ core. Consider assigning values of such properties into a local variable if you need to modify or read them multiple times at a single code location:

using Godot;

public partial class YourCustomClass : Node3D
{
    private void ExpensiveReposition()
    {
        for (var i = 0; i < 10; i++)
        {
            // Position is read and set 10 times which incurs native interop.
            // Furthermore the object is repositioned 10 times in 3D space which
            // takes additional time.
            Position += new Vector3(i, i);
        }
    }

    private void Reposition()
    {
        // A variable is used to avoid native interop for Position on every loop.
        var newPosition = Position;
        for (var i = 0; i < 10; i++)
        {
            newPosition += new Vector3(i, i);
        }
        // Setting Position only once avoids native interop and repositioning in 3D space.
        Position = newPosition;
    }
}

Passing raw arrays (such as byte[]) or string to Godot's C# API requires marshalling which is comparatively pricey.

The implicit conversion from string to NodePath or StringName incur both the native interop and marshalling costs as the string has to be marshalled and passed to the respective native constructor.

Uso de los paquetes NuGet en Godot

Los paquetes NuGet pueden ser instalados y usados en Godot, como en cualquier proyecto C#. Muchos IDEs pueden añadir paquetes directamente. También se pueden añadir manualmente añadiendo la referencia del paquete en el archivo .csproj ubicado en la raíz del proyecto:

    <ItemGroup>
        <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
    </ItemGroup>
    ...
</Project>

A partir de Godot 3.2.3, Godot descarga y configura automáticamente los paquetes NuGet recién agregados la próxima vez que compila el proyecto.

Evaluando tu código C#

The following tools may be used for performance and memory profiling of your managed code:

  • JetBrains Rider with dotTrace/dotMemory plugin.

  • Standalone JetBrains dotTrace/dotMemory.

  • Visual Studio.

Profiling managed and unmanaged code at once is possible with both JetBrains tools and Visual Studio, but limited to Windows.