TExcelTAD
Home › Godot 4 with GDScript › C# in Godot

C# in Godot

Godot has two official scripting languages: GDScript, built into every editor, and C#, available in the separate .NET build of the editor. Both use the same nodes, signals and resources, and one project can mix them. This lesson shows when C# is worth it, how a Godot C# script is shaped, and what the .NET build changes.

When to choose C#

Pick GDScript when Pick C# when
you want the fastest edit-run loop and no external tools you or your team already know C# (Unity background, .NET tools)
you target the web you need heavy CPU work in scripts (C# runs compiled .NET code; GDScript is interpreted)
you want every tutorial and asset to match your code you want NuGet packages, a strong IDE refactoring story, LINQ, generics
the game is small or mostly engine work (physics, rendering, UI) the game has large systems: simulation, procedural generation, complex AI

Facts to check before you commit (from the official docs at the time of writing; check the current page for your version):

  • You need the .NET build of the editor and the .NET SDK installed separately. The docs for current 4.x releases (4.5 to 4.7) ask for .NET 8 or later, and .NET 9 or later to export a C# project to Android. The development docs for the next version raise the minimum to .NET 10, so check the "C# basics" page for the version you install.
  • C# projects cannot currently be exported to the web in Godot 4. If the browser is a target, use GDScript.
  • Desktop exports (Windows, macOS, Linux) are fully supported; Android and iOS support is marked experimental.
  • The .NET editor can still open GDScript projects; the standard editor cannot run C# scripts.

If you know C# from the C# course or the Unity course, most of it carries over. The engine API is the same as GDScript's with names converted to PascalCase: move_and_slide() becomes MoveAndSlide(), is_on_floor() becomes IsOnFloor(), velocity becomes Velocity.

The shape of a Godot C# script

csharp
using Godot;

public partial class Player : CharacterBody2D
{
    [Signal]
    public delegate void HealthChangedEventHandler(int oldHealth, int newHealth);

    [Export] public float Speed { get; set; } = 220.0f;
    [Export] public float JumpVelocity { get; set; } = -400.0f;
    [Export] public int MaxHealth { get; set; } = 3;

    private int _health;
    private AnimatedSprite2D _sprite;

    public override void _Ready()
    {
        _health = MaxHealth;
        _sprite = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
    }

    public override void _PhysicsProcess(double delta)
    {
        Vector2 velocity = Velocity;
        if (!IsOnFloor())
            velocity += GetGravity() * (float)delta;
        if (Input.IsActionJustPressed("jump") && IsOnFloor())
            velocity.Y = JumpVelocity;

        float direction = Input.GetAxis("move_left", "move_right");
        velocity.X = direction * Speed;
        Velocity = velocity;
        MoveAndSlide();
    }

    public void TakeDamage(int amount)
    {
        int old = _health;
        _health = Mathf.Max(_health - amount, 0);
        EmitSignal(SignalName.HealthChanged, old, _health);
    }
}

Line by line, the Godot-specific parts:

  • partial class is required. Godot's source generators write the other half of the class at build time: the glue that registers your properties, methods and signals with the engine. Without partial the project fails to build.
  • The class name must match the file name (Player.cs), and the class derives from a Godot class (Node, Node2D, CharacterBody2D, Resource, ...).
  • [Export] on a field or property shows it in the inspector, like @export in GDScript. Exported members need a type the engine can store: numbers, strings, Godot structs (Vector2, Color), nodes and resources, Godot.Collections.Array/Dictionary, enums.
  • [Signal] goes on a delegate whose name ends in EventHandler. The generator creates the signal HealthChanged (the suffix is removed), a C# event with the same name, and a constant SignalName.HealthChanged.
  • EmitSignal(SignalName.HealthChanged, old, _health) emits it. Use the generated SignalName constants rather than strings; typos then fail at compile time.
  • delta is a double in C#. Most engine math uses float, hence the cast.
  • Velocity is a struct property: copy it into a local, change the copy, then assign it back. Velocity.Y = 5 doesn't compile.

Connecting signals in C#

The generated events make signals feel like normal C# events:

csharp
public partial class Hud : CanvasLayer
{
    [Export] public Player Player { get; set; }
    private Label _label;

    public override void _Ready()
    {
        _label = GetNode<Label>("HealthLabel");
        Player.HealthChanged += OnHealthChanged;          // custom signal
        GetNode<Button>("PauseButton").Pressed += OnPausePressed;   // engine signal
    }

    private void OnHealthChanged(int oldHealth, int newHealth) => _label.Text = 
quot;HP {newHealth}"; private void OnPausePressed() => GetTree().Paused = !GetTree().Paused; }

You can also use the engine API directly, which supports flags such as one-shot connections:

csharp
Player.Connect(Player.SignalName.HealthChanged,
    Callable.From<int, int>(OnHealthChanged), (uint)ConnectFlags.OneShot);

Signals connected in the editor's Node dock work too: the method must exist on the C# class with matching parameters.

A runnable model of the generated code

The generator is not magic. Here is a plain C# model of the two halves of partial class Player: what you write, and roughly what gets generated (an event, a name constant and an EmitSignal that dispatches by name). It runs on this site:

csharp · try it yourself
using System;

var player = new Player();
player.HealthChanged += (oldHp, newHp) => Console.WriteLine(
quot;HUD: {oldHp} -> {newHp}"); player.HealthChanged += (oldHp, newHp) => { if (newHp == 0) Console.WriteLine("Game over"); }; player.TakeDamage(1); player.TakeDamage(5); // ---- The half you write ---- public partial class Player { public delegate void HealthChangedEventHandler(int oldHealth, int newHealth); // [Signal] private int _health = 3; public void TakeDamage(int amount) { int old = _health; _health = Math.Max(_health - amount, 0); EmitSignal(SignalName.HealthChanged, old, _health); } } // ---- Roughly the half Godot's source generator writes ---- public partial class Player { public static class SignalName { public const string HealthChanged = "HealthChanged"; } private HealthChangedEventHandler _healthChanged; public event HealthChangedEventHandler HealthChanged { add => _healthChanged += value; remove => _healthChanged -= value; } private void EmitSignal(string name, params object[] args) { if (name == SignalName.HealthChanged) _healthChanged?.Invoke((int)args[0], (int)args[1]); } }
HUD: 3 -> 2
HUD: 2 -> 0
Game over

Custom resources and mixing languages

A C# resource class needs [GlobalClass] to appear in the New Resource dialog, like class_name in GDScript:

csharp
using Godot;

[GlobalClass]
public partial class EnemyStats : Resource
{
    [Export] public int MaxHealth { get; set; } = 3;
    [Export] public float Speed { get; set; } = 80.0f;
}

Mixing languages works through the engine. GDScript can call a C# node's public methods and properties by their C# names (player.TakeDamage(1), player.Speed), and C# can call GDScript with node.Call("take_damage", 1) and node.Get("speed"). Keep cross-language calls at boundaries (a C# simulation, GDScript UI), not in every frame.

Setting up the .NET build

  1. Install the .NET SDK (version per the docs for your Godot release).
  2. Download the .NET variant of Godot 4 from godotengine.org and run it.
  3. In a project, attach a script and choose C# as the language. On the first C# script, Godot creates a .csproj and .sln next to project.godot. Commit them.
  4. Choose your IDE in Editor > Editor Settings > Dotnet > Editor: Visual Studio, VS Code (with Microsoft's C# extension), or JetBrains Rider. See Godot Builds, VS Code & the Debugger.
  5. Press Build (the hammer icon at the top right) or just run the game; Godot builds the assembly first.

Note: Calls between C# and the engine cross a boundary, and every Godot.Collections.Array access is a call into the engine. In hot loops, copy engine data into ordinary C# arrays or List<T>, work on those, and write the results back.

Test yourself

Why must a Godot C# script be declared partial?

  1. For faster compilation
  2. Godot's source generators add the other half of the class (signal events, property and method registration)
  3. C# requires it for every class
  4. So GDScript can inherit from it

How do you declare a custom signal Died with no arguments in C#?

  1. [Signal] public event Action Died;
  2. [Signal] public delegate void DiedEventHandler();
  3. signal Died();
  4. [Export] public Signal Died;

Your game must run in the browser. Which language should its scripts use in Godot 4?

  1. C#
  2. GDScript
  3. Either; both export to the web
  4. Only C++ via GDExtension