Up to date

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

C# 기초

소개

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.

주의

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.

참고

이것은 C# 언어 전체에 대한 본격적인 튜토리얼이 아닙니다. 문법이나 기능에 익숙하지 않다면 Microsoft C# 가이드를 보거나 다른 적합한 설명을 찾아보세요.

준비사항

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.

중요

64-bit 버전의 Godot을 사용하고 있다면 64-bit 버전의 SDK를 설치해야 합니다.

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.

외부 편집기 설정

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

외부 편집기를 설정하는 방법은 아래 구획들을 확인하십시오:

JetBrains Rider

"준비사항" 구획을 읽은 후, JetBrains Rider 를 설치할 수 있습니다.

Godot의 편집기 → 편집기 설정 메뉴에서:

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

Rider 에서:

  • MSBuild version.NET Core 로 설정.

  • Godot support 플러그인을 설치.

Visual Studio Code

"준비사항" 구획을 읽은 후, Visual Studio Code (VS Code)를 설치할 수 있습니다.

Godot의 편집기 → 편집기 설정 메뉴에서:

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

Visual Studio Code에서:

참고

Linux를 사용한다면 C# 플러그인을 사용하기 위해 Mono SDK 를 설치해야 합니다.

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(Windows만 가능)

최신 버전의 Visual Studio 를 설치하십시오. 올바른 워크로드를 선택했다면 Visual Studio 내에 필요한 SDK가 포함되어있을 것이므로, "준비사항" 구획에 설명된 것들을 직접 설치하지 않아도 됩니다.

While installing Visual Studio, select this workload:

  • .NET desktop development

Godot의 편집기 → 편집기 설정 메뉴에서:

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

참고

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 delete the NuGet.Config file. When you build your Godot project again, the file will be automatically created with default values.

C# 스크립트 만들기

Godot용 C# 을 성공적으로 설정한 후, 씬의 노드 메뉴에서 스크립트 붙이기 를 눌렀을 때, 다음 설정이 표시되어야 합니다:

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

프로젝트 설정과 작업 흐름

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.

예제

여기 동작을 설명하는 주석이 붙은 C# 스크립트가 있습니다.

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.

참고

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

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

C#과 GDScript와의 일반적인 차이

GDScript/C++에서는 snake_case를 쓰지만 C# API는 PascalCase를 씁니다. 가능하면 공백과 getters/setters이 속성으로 변환됩니다. 일반적으로 C# Godot API는 합리적으로 가능한 것처럼 관용적이도록 노력합니다.

더 자세한 내용은, C#과 GDScript의 API 차이점 페이지를 참고하세요.

경고

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

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

현재 문제와 알려진 문제

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.

  • 편집기 플러그인을 작성하는 것은 가능하지만, 현재로썬 상당히 복잡합니다.

  • 내보낸 변수를 제외하고, 현재 상태는 핫 리로드 중일 때 저장되고 복원되지 않습니다.

  • 첨부된 C# 스크립트가 파일 이름과 일치하는 클래스 이름을 가진 클래스를 참조해야 합니다.

  • 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.

Godot에서 C#의 퍼포먼스

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.

Godot에서 NuGet 패키지 사용하기

NuGet 패키지를 설치하여 프로젝트처럼, Godot와 사용할 수 있습니다. 많은 IDE는 직접 패키지를 추가할 수 있습니다. 또한 프로젝트 루트에 있는 .csproj 파일에 패키지 참조를 수동으로 추가할 수 있습니다:

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

Godot 버전 3.2.3부터는 프로젝트를 빌드한 후 새로 추가된 NuGet 패키지를 자동으로 다운로드 및 설정합니다.

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.