C# basics

Introduction

This page provides a brief introduction to C#, both what it is andhow to use it in Godot. Afterwards, you may want to look athow to use specific features, read about thedifferences between the C# and the GDScript API,and (re)visit theScripting section of thestep-by-step tutorial.

C# is a high-level programming language developed by Microsoft. In Godot,it is implemented with .NET 8.0.

Attention

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

Note

This isnot a full-scale tutorial on the C# language as a whole.If you aren't already familiar with its syntax or features, see theMicrosoft C# guideor look for a suitable introduction elsewhere.

Prerequisites

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

In summary, you must have installed the .NET SDKand the .NET-enabledversion of Godot.

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

Important

Be sure to install the 64-bit version of the SDK(s)if you are using the 64-bit version of Godot.

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

Configuring an external editor

C# support in Godot's built-in script editor is minimal. Consider using anexternal IDE or editor, such asVisual Studio CodeorVisual Studio. These provide autocompletion, debugging, and otheruseful features for C#. To select an external editor in Godot,click onEditor → Editor Settings and scroll down toDotnet. UnderDotnet, click onEditor, and select yourexternal editor of choice. Godot currently supports the followingexternal editors:

  • Visual Studio 2022

  • Visual Studio Code

  • MonoDevelop

  • Visual Studio for Mac

  • JetBrains Rider

See the following sections for how to configure an external editor:

JetBrains Rider

After reading the "Prerequisites" section, you can download and installJetBrains Rider.

In Godot'sEditor → Editor Settings menu:

  • SetDotnet ->Editor ->External Editor toJetBrains Rider.

In Rider:

  • SetMSBuild version to.NET Core.

  • If you are using a Rider version below 2024.2, install theGodot support plugin. This functionality is now built into Rider.

Visual Studio Code

After reading the "Prerequisites" section, you can download and installVisual Studio Code (aka VS Code).

In Godot'sEditor → Editor Settings menu:

  • SetDotnet ->Editor ->External Editor toVisual Studio Code.

In Visual Studio Code:

  • Install theC# extension.

To configure a project for debugging, you need atasks.json andlaunch.json file inthe.vscode folder with the necessary configuration.

Here is an examplelaunch.json:

{"version":"0.2.0","configurations":[{"name":"Play","type":"coreclr","request":"launch","preLaunchTask":"build","program":"${env:GODOT4}","args":[],"cwd":"${workspaceFolder}","stopAtEntry":false,}]}

For this launch configuration to work, you need to either setup a GODOT4environment variable that points to the Godot executable, or replaceprogramparameter with the path to the Godot executable.

Here is an exampletasks.json:

{"version":"2.0.0","tasks":[{"label":"build","command":"dotnet","type":"process","args":["build"],"problemMatcher":"$msCompile"}]}

Now, when you start the debugger in Visual Studio Code, your Godot project will run.

Visual Studio (Windows only)

Download and install the latest version ofVisual Studio.Visual Studio will include the required SDKs if you have the correctworkloads selected, so you don't need to manually install the thingslisted in the "Prerequisites" section.

While installing Visual Studio, select this workload:

  • .NET desktop development

In Godot'sEditor → Editor Settings menu:

  • SetDotnet ->Editor ->External Editor toVisual Studio.

Note

If you see an error like "Unable to find package Godot.NET.Sdk",your NuGet configuration may be incorrect and need to be fixed.

A simple way to fix the NuGet configuration file is to regenerate it.In a file explorer window, go to%AppData%\NuGet. Rename or deletetheNuGet.Config file. When you build your Godot project again,the file will be automatically created with default values.

To debug your C# scripts using Visual Studio, open the .sln file that is generatedafter opening the first C# script in the editor. In theDebug menu, go to theDebug Properties menu item for your project. Click theCreate a new profilebutton and chooseExecutable. In theExecutable field, browse to the pathof the C# version of the Godot editor, or type%GODOT4% if you have created anenvironment variable for the Godot executable path. It must be the path to the main Godotexecutable, not the 'console' version. For theWorking Directory, type a single period,., meaning the current directory. Also check theEnable native code debuggingcheckbox. You may now close this window, click downward arrow on the debug profiledropdown, and select your new launch profile. Hit the green start button, and yourgame will begin playing in debug mode.

Creating a C# script

After you successfully set up C# for Godot, you should see the following optionwhen selectingAttach Script in the context menu of a node in your scene:

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

Note that while some specifics change, most concepts work the samewhen using C# for scripting. If you're new to Godot, you may want to followthe tutorials onScripting languages at this point.While some documentation pages still lack C# examples, most notionscan be transferred from GDScript.

Project setup and workflow

When you create the first C# script, Godot initializes the C# project filesfor 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 yourversion control system. Everything under.godot can be safely added to theignore list of your VCS.When troubleshooting, it can sometimes help to delete the.godot/mono folderand let it regenerate.

Example

Here's a blank C# script with some comments to demonstrate how it works.

usingGodot;publicpartialclassYourCustomClass:Node{// Member variables here, example:privateint_a=2;privatestring_b="textvar";publicoverridevoid_Ready(){// Called every time the node is added to the scene.// Initialization here.GD.Print("Hello from C# to Godot :)");}publicoverridevoid_Process(doubledelta){// 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'sprint function are available in theGD static class which is part oftheGodot namespace. For a full list of methods in theGD class, see theclass reference pages for@GDScript and@GlobalScope.

Note

Keep in mind that the class you wish to attach to your node should have the samename as the.cs file. Otherwise, you will get the following error:

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

General differences between C# and GDScript

The C# API usesPascalCase instead ofsnake_case in GDScript/C++.Where possible, fields and getters/setters have been converted to properties.In general, the C# Godot API strives to be as idiomatic as is reasonably possible.

For more information, see theC# API differences to GDScript page.

Warning

You need to (re)build the project assemblies whenever you want to see newexported variables or signals in the editor. This build can be manuallytriggered by clicking theBuild button in the top right corner of theeditor.

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

You will also need to rebuild the project assemblies to apply changes in"tool" scripts.

Current gotchas and known issues

As C# support is quite new in Godot, there are some growing pains and thingsthat need to be ironed out. Below is a list of the most important issuesyou should be aware of when diving into C# in Godot, but if in doubt, alsotake a look over the officialissue tracker for .NET issues.

  • Writing editor plugins is possible, but it is currently quite convoluted.

  • State is currently not saved and restored when hot-reloading,with the exception of exported variables.

  • Attached C# scripts should refer to a class that has a class namethat matches the file name.

  • There are some methods such asGet()/Set(),Call()/CallDeferred()and signal connection methodConnect() that rely on Godot'ssnake_case APInaming conventions.So when using e.g.CallDeferred("AddChild"),AddChild will not work becausethe API is expecting the originalsnake_case versionadd_child. However, youcan use any custom properties or methods without this limitation.Prefer using the exposedStringName in thePropertyName,MethodName andSignalName to avoid extraStringName 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.xreleases.

Common pitfalls

You might encounter the following error when trying to modify some values in Godotobjects, e.g. when trying to change the X coordinate of aNode2D:

publicpartialclassMyNode2D:Node2D{publicoverridevoid_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, aVector2) in C# arecopied on assignment, meaning that when you retrieve such an object from aproperty or an indexer, you get a copy of it, not the object itself. Modifyingsaid copy without reassigning it afterwards won't achieve anything.

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

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

Since C# 10, it is also possible to usewith expressionson structs, allowing you to do the same thing in a single line.

Position=Positionwith{X=100.0f};

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

Performance of C# in Godot

See also

For a performance comparison of the languages Godot supports,seeWhich programming language is fastest?.

Most properties of Godot C# objects that are based onGodotObject(e.g. anyNode likeControl orNode3D likeCamera3D) require native (interop) calls as they talk toGodot's C++ core.Consider assigning values of such properties into a local variable if you need to modify or read them multiple times ata single code location:

usingGodot;publicpartialclassYourCustomClass:Node3D{privatevoidExpensiveReposition(){for(vari=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+=newVector3(i,i);}}privatevoidReposition(){// A variable is used to avoid native interop for Position on every loop.varnewPosition=Position;for(vari=0;i<10;i++){newPosition+=newVector3(i,i);}// Setting Position only once avoids native interop and repositioning in 3D space.Position=newPosition;}}

Passing raw arrays (such asbyte[]) orstring to Godot's C# API requires marshalling which iscomparatively pricey.

The implicit conversion fromstring toNodePath orStringName incur both the native interop and marshallingcosts as thestring has to be marshalled and passed to the respective native constructor.

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 inthe.csproj file located in the project root:

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

As of Godot 3.2.3, Godot automatically downloads and sets up newly added NuGetpackages the next time it builds the project.

Profiling your C# code

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.


User-contributed notes

Please read theUser-contributed notes policy before submitting a comment.