All articles

Godot 4 and C#: node lifecycle, signals and the main thread

Godot.NET.Sdk and partial classes, the _Ready/_Process order, [Signal] and ToSignal, CallDeferred, protecting the main thread with Task.Run, user:// paths and headless export.

t.Turgay
Godot 4 and C#: node lifecycle, signals and the main thread

The .NET edition of Godot lets you attach C# scripts to nodes in a scene. The project is an ordinary .csproj built by dotnet; the engine loads the assembly and maps script classes to nodes. Most bugs in this model come from four questions: when a node becomes usable, which types a signal can carry, when tree-changing calls may run, and the rule that the scene tree is only modified from the main thread. The examples below are independent fragments written against the Godot 4 API.

Godot.NET.Sdk and partial script classes

The game project uses Godot.NET.Sdk in its Sdk attribute, at the same version as the engine. The project file generated by the editor sets EnableDynamicLoading; keep it, because the engine loads the assembly as a component. Writing the target framework explicitly also prevents an unexpected framework from being added after an engine upgrade.

Script classes must be partial because Godot source generators add signal, property and method registrations to another part of the class. The class name must match the file name. Rules that do not depend on engine types can live in separate class libraries and run under dotnet test without starting Godot.

<!-- Game.csproj: the engine-facing project -->
<Project Sdk="Godot.NET.Sdk/4.7.2">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <EnableDynamicLoading>true</EnableDynamicLoading>
  </PropertyGroup>
  <ItemGroup>
    <!-- Engine-independent rules live in a plain class library. -->
    <ProjectReference Include="..\Rules\Rules.csproj" />
  </ItemGroup>
</Project>

// Radar.cs: the file name and the class name must match.
using Godot;

public partial class Radar : Node2D
{
    [Export] public float SweepDegreesPerSecond { get; set; } = 90f;

    public override void _Process(double delta) =>
        RotationDegrees += SweepDegreesPerSecond * (float)delta;
}

Godot — C# basics

The order of _EnterTree, _Ready and _Process

When the constructor runs, the node is not in the scene tree yet: GetNode cannot reach children and exported values from the scene are assigned later. _EnterTree runs when the node enters the tree, parent first and then children. _Ready runs after all of a node's children are ready, so children finish their _Ready before the parent does.

_Process runs every frame with a variable delta; _PhysicsProcess runs at the fixed physics rate. If a rule must not depend on frame rate, multiply by delta or use a fixed step. _ExitTree is the place for cleanup: a node that subscribes to an event on a long-lived object with += should unsubscribe with -= when it leaves the tree. Do not rely on automatic cleanup, especially when the handler is a lambda.

Godot — Overridable functions

Signals: declaration, emission and await

In C#, a signal is a delegate marked with the Signal attribute whose name ends with EventHandler. The source generator produces a C# event with the same base name and a SignalName constant. Passing SignalName to EmitSignal instead of a string moves typos to compile time. Signal parameters must be Variant-compatible: primitive numbers, strings, Godot types and GodotObject instances.

ToSignal turns a signal into an awaitable, so waiting for the next frame or for a timer needs no separate state machine. After the await, check that the node is still valid. If the scene changed meanwhile, the continuation could touch a freed object.

using Godot;

public partial class Reactor : Node
{
    [Signal] public delegate void HeatChangedEventHandler(float heat);

    private float _heat;

    public void AddHeat(float amount)
    {
        _heat += amount;
        EmitSignal(SignalName.HeatChanged, _heat);
    }

    public async void CoolDown()
    {
        // Wait for a one-shot timer, then for the next processed frame.
        await ToSignal(GetTree().CreateTimer(0.5), SceneTreeTimer.SignalName.Timeout);
        await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
        if (!IsInstanceValid(this) || !IsInsideTree()) return;
        _heat = 0;
        EmitSignal(SignalName.HeatChanged, _heat);
    }
}

// Subscriber: reactor.HeatChanged += OnHeatChanged;  (remove it again in _ExitTree)

Godot — C# signals

CallDeferred and Callable.From

If some tree-changing operations run inside the current call chain, later lines can operate on a node that has already left the tree. In current Godot 4 releases, changing the scene removes the current scene immediately; a GetTree call later in the same method no longer returns the expected tree. Adding or removing collision objects during physics callbacks is another operation that should be deferred.

CallDeferred moves the call to the idle phase of the frame. In C#, wrap a lambda with Callable.From and queue it with CallDeferred. Calls queued in the same frame run in the order they were queued. That gives dependent startup steps, such as building a menu and then opening a panel, a readable order.

The main thread, Task.Run and the synchronization context

Interacting with the active scene tree is not thread-safe. Writing a save file, decoding a large JSON document or reading a database on the main thread lengthens the frame and makes the game stutter. The recommended shape is to capture an immutable snapshot on the main thread, hand the heavy work to the thread pool with Task.Run, and apply the result on the main thread again.

Godot installs a synchronization context for the main thread, so an await inside a node method resumes on the main thread unless ConfigureAwait(false) is used. The lambda passed to Task.Run must not touch nodes. Some libraries that expose async APIs actually run synchronously; Microsoft.Data.Sqlite is a well-known example.

// CaptureSnapshot, SaveStore and ShowToast are illustrative.
public partial class SavePanel : Control
{
    private bool _saving;

    private async void OnSavePressed()
    {
        if (_saving) return;
        _saving = true;
        var snapshot = CaptureSnapshot();            // main thread: read nodes once
        try
        {
            // Worker thread: no node access inside this lambda.
            await Task.Run(() => SaveStore.Write(snapshot));
            if (IsInstanceValid(this)) ShowToast("Saved");   // back on the main thread
        }
        catch (IOException e)
        {
            if (IsInstanceValid(this)) ShowToast("Save failed: " + e.Message);
        }
        finally { _saving = false; }
    }
}

Godot — Thread-safe APIs

res://, user:// and .NET file APIs

res:// points to project resources, which live inside the pack file of an exported game; it is not a place to write at runtime. Save, settings and log files belong under user://. If the project defines a custom user directory name, Windows places that folder under the user's application data directory.

System.IO does not understand the user:// prefix, so call ProjectSettings.GlobalizePath before handing a path to .NET file APIs. The same conversion only yields a real file path for res:// in the editor or when running from the project folder. In an exported game, resources must be read through the engine's file API.

Godot — File paths in Godot projects

Headless export, user arguments and Obfuscar

--headless runs the engine without opening a window. A release pipeline first runs --import, then calls --export-release with the preset name from export_presets.cfg. C# projects need the .NET export templates for the same engine version. Values after -- on the command line are not interpreted by the engine and can be read with OS.GetCmdlineUserArgs, a convenient way to request an automatic screenshot or a test scene.

If exported .NET assemblies go through an obfuscator such as Obfuscar, review every reflection-based name contract first. System.Text.Json binds record constructor parameters by name; renaming those parameters breaks deserialization. The assembly in which the engine finds script classes must also stay untouched. A short startup run with --headless and --quit-after after obfuscation catches these failures before a package is published.

Godot — Command line tutorial

Obfuscar

Related technical articles

You have reached the end of this orbit.
Explore more articles
turgay.A little code, a few pixels, a lot of curiosity.© 2026 · Made on Earth