C# / .NET in Godot 4.7
Build after every edit: python scripts/cs_build.py returns errors as {file, line, code, msg}. Use --doctor to check the setup and --init to create the csproj and sln exactly like the 4.7 editor does.
The engine runs the last built assembly in .godot/mono/temp/bin/, so build before any smoke run.
C# names: api_lookup.py Node3D.look_at prints Node3D.LookAt(Vector3, Vector3?, bool). C# names also work as queries.
Project setup (verified 4.7.2 template)
<Project Sdk="Godot.NET.Sdk/4.7.2">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework Condition=" '$(GodotTargetPlatform)' == 'android' ">net9.0</TargetFramework>
<EnableDynamicLoading>true</EnableDynamicLoading>
</PropertyGroup>
</Project>
- The
Godot.NET.Sdk/x.y.zversion must equal the engine version. Bump it when you upgrade Godot. net8.0 is the minimum; net9.0+ is allowed.<Nullable>enable</Nullable>is recommended. project.godotneeds"C#"inconfig/featuresand[dotnet] project/assembly_name. The assembly name must match the csproj name.- NuGet packages work normally (
dotnet add package). Assemblies must be pure managed code, or ship native libraries for every target platform. - Not supported: web export of C# projects (still true in 4.7; use GDScript for web builds). Android needs net9.0 (the template handles it). iOS works. Desktop works everywhere.
Script rules (the source generators depend on them)
public partial class Player : CharacterBody3D. The file name must equal the class name (Player.cs). Namespaces are fine. Godot-derived classes must bepartial.[GlobalClass]registers the class in the Create dialog and as an exportable Resource type, like GDScriptclass_name.[Tool]runs the class in the editor.- Exports:
[Export] public float Speed { get; set; } = 5f;plus[ExportGroup("Movement")],[ExportSubgroup],[ExportCategory],[Export(PropertyHint.Range, "0,100,1")]and[ExportToolButton("Bake")] public Callable BakeButton => Callable.From(Bake);. - Signals:
[Signal] public delegate void HitEventHandler(int damage);. The suffix is required. The generator creates eventHitandSignalName.Hit. Emit withEmitSignal(SignalName.Hit, 5)and connect withenemy.Hit += OnHit;. - Use
SignalName.*,MethodName.*andPropertyName.*(generatedStringNames) wherever the API wants a name, so you never allocate strings. - Structs are copied:
Position.X = 5won't compile (CS1612). WritePosition = Position with { X = 5 };.
Signal lifetime (official rules)
Godot disconnects everything when either object is freed, except:
+=to a custom[Signal], when the receiver is freed first, and- lambdas that capture variables. Godot can't tie them to an instance, and
Callable.Fromdoesn't help. In both cases, unsubscribe with-=in_ExitTree(keep the delegate in a field for lambdas). Otherwise, emitting into a freed object throwsObjectDisposedException.
Performance and correctness
- Cache input actions, groups and other names as
static readonly StringName. Passing"jump"every frame allocates. - Use
System.Collections.Genericfor internal logic. UseGodot.Collections.Array<T>/Dictionary<TK,TV>only at the Godot boundary (exports, signals, GDScript calls). Each crossing marshals the data. - Packed arrays (
Vector3[],byte[]) are copied on every API call. Read a mesh array once and work on the copy. - Avoid LINQ and closures in
_Process/_PhysicsProcesshot loops. PreferGetNode<T>()once in_Readyand keep the result in a field. - Culture bug:
$"{1.5f}",float.ParseandToString()follow the OS locale (1,5in Italian, German, …). UseCultureInfo.InvariantCulturefor saves, network data, JSON and UI number formats. (Observed on a 4.7.2 test machine.) - Exceptions in callbacks are logged, not fatal. Watch the Output/Debugger panel, or
run_godot.py smokeerrors. GD.Printallocates. Remove it from hot paths, or put it behind#if DEBUGorOS.IsDebugBuild().
Async
await ToSignal(GetTree().CreateTimer(1.0), SceneTreeTimer.SignalName.Timeout);awaits a signal on the main thread.- Run CPU work on
Task.Run/WorkerThreadPool, then get back to the main thread withCallDeferredorCallable.From(...).CallDeferred()before you touch nodes. - Await anything inside
_Ready/_Processonly through anasync voidhandler, and keep it short. CheckIsInstanceValid(this)after awaits.
GDScript ↔ C#
- From C#:
var gd = GetNode("Inventory"); gd.Call("add_item", "sword", 2); var n = gd.Get("count").AsInt32();. Connect to its signals withgd.Connect("changed", Callable.From<int>(OnChanged)). - From GDScript: C# public members appear with their C# names (
node.Speed,node.Damage(5)). Signals keep their C# names (node.Hit.connect(...)). - Create GDScript objects from C#:
GD.Load<GDScript>("res://x.gd").New().AsGodotObject(). Variant:Variant.From(x),v.As<T>(),v.AsInt32(),v.VariantType. ReturnVariantfrom methods GDScript calls dynamically.
Patterns, interop and editor/hot-reload notes (compiled by the tests): references/patterns.md.