C# の基本

はじめに

警告

C#サポートは、Godot 3.0以降で利用可能な新しい機能です。そのため、依然としていくつかの問題に遭遇したり、ドキュメントで改善できる箇所が見つかる場合があります。 GodotのC#に関する問題は engine GitHubページにて、ドキュメントの問題は documentation GitHubページにて報告をお願いします。

このページでは、C#の概要と、Godotでの使用方法の両方について簡単に紹介しています。その後、特定の機能を使用する方法C#とGDScript APIの違いについて読み、(再び)ステップバイステップ チュートリアルのスクリプトセクションを参照してください。

C#は、マイクロソフトが開発した高水準プログラミング言語です。Godotでは、C# 8.0の完全なサポートを含むMono 6.x .NETフレームワークで実装されています。Monoは、C#および共通言語ランタイムのECMA標準に基づいたMicrosoftの.NET Frameworkのオープンソース実装です。その機能を確認するための良い出発点は、Monoドキュメントの互換性ページです。

注釈

これはC#言語全体に関する本格的なチュートリアルではありません。まだその構文や機能に慣れていなければ、Microsoft C#ガイドや他の適切な入門書を参照してください。

Godot用のC#のセットアップ

前提条件

Install the latest stable version of the .NET SDK, previously known as the .NET Core SDK.

From Godot 3.2.3 onwards, installing Mono SDK is not a requirement anymore, except it is required if you are building the engine from source.

Godot bundles the parts of Mono 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, which needs to be installed separately.

In summary, you must have installed the .NET SDK and the Mono-enabled version of Godot.

その他の注意事項

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, install the latest stable version of Mono, and make sure to follow the steps to enable Mono support in your build as outlined in the Monoでコンパイルする 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 Mono. Under Mono, click on Editor, and select your external editor of choice. Godot currently supports the following external editors:

  • Visual Studio 2019

  • 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 install JetBrains Rider.

In Godot's Editor → Editor Settings menu:

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

  • Set Mono -> Builds -> Build Tool to dotnet CLI.

In Rider:

  • Set MSBuild version to .NET Core.

  • Install the Godot support plugin.

Visual Studio Code

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

In Godot's Editor → Editor Settings menu:

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

  • Set Mono -> Builds -> Build Tool to dotnet CLI.

Visual Studio Codeの場合:

注釈

If you are using Linux you need to install the Mono SDK for the C# tools plugin to work.

To configure a project for debugging open the Godot project folder in VS Code. Go to the Run tab and click on Add Configuration.... Select C# Godot from the dropdown menu. Open the tasks.json and launch.json files that were created. Change the executable setting in launch.json and command settings in tasks.json to your Godot executable path. Now, when you start the debugger in VS Code, your Godot project will run.

Visual Studio (Windows のみ)

Download and install the latest version of Visual Studio. Visual Studio will include the required SDKs if you have the correct workloads selected, so you don't need to manually install the things listed in the "Prerequisites" section.

Visual Studioのインストールに関する注意事項:

  • .NETを使ったモバイル開発

  • .NET Core cross-platform development

In Godot's Editor → Editor Settings menu:

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

  • Set Mono -> Builds -> Build Tool to dotnet CLI.

Next, you can download the Godot Visual Studio extension from github here. Double click on the downloaded file and follow the installation process.

注釈

The option to debug your game in Visual Studio may not appear after installing the extension. To enable debugging, there is a workaround for Visual Studio 2019. There is a separate issue about this problem in Visual Studio 2022.

注釈

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#スクリプトの作成

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

../../../_images/attachcsharpscript.png

一部の仕様は変更されますが、スクリプトにC#を使用する場合でも、ほとんどの概念はGDScriptと同じように機能することに注意してください。Godotを初めて使用する場合は、この時点で スクリプト言語 のチュートリアルに従うことをお勧めします。ドキュメント内のいくつかの場所にはまだC#の例が欠けていますが、ほとんどの概念はGDScriptから簡単に移行できます。

プロジェクトの設定とワークフロー

最初のC#スクリプトを作成すると、GodotはGodotプロジェクトのC#プロジェクトファイルを初期化します。これには、C#ソリューション(.sln)とプロジェクトファイル(.csproj)の生成、およびいくつかのユーティリティファイルとフォルダ(.mono および Properties/AssemblyInfo.cs)の生成が含まれます。 .mono を除くこれらすべては重要であり、バージョン管理システム(VCS)にコミットする必要があります。 .mono は、VCSの無視リストに安全に追加できます。 .mono フォルダを削除して再生成すると、トラブルシューティングの際に役立つ場合があります。

以下に、空白のC#スクリプトと、その動作を示すコメントを示します。

using Godot;
using System;

public 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(float delta)
    {
        // Called every frame. Delta is time since the last frame.
        // Update game logic here.
    }
}

ご覧のとおり、Godotの print 関数のようなGDScriptのグローバル スコープの関数は、Godot 名前空間の一部である GD クラスで使用できます。GD クラスのメソッドの一覧については、@GDScript および @GlobalScope のクラス リファレンス ページを参照してください。

注釈

ノードにアタッチしたいクラスは .cs ファイルと同じ名前にする必要があることに注意してください。そうしないと、次のエラーが発生し、シーンを実行できません: "Cannot find class XXX for script res://XXX.cs"

C#とGDScriptの一般的な違い

C# APIはGDScript/C++の snake_case の代わりに PascalCase を使います。 可能であれば、フィールドとゲッター/セッターはプロパティに変換されています。一般的に、C# Godot APIは合理的に可能な限り慣用的であるように努めています。

詳細については、C# API differences to GDScript ページを参照してください。

警告

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 word Build in the top right corner of the editor. You can also click Mono at the bottom of the editor window to reveal the Mono panel, then click the Build Project button.

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

現在の課題と既知の問題

GodotでのC#のサポートは非常に新しいため、いくつかの苦労や解決する必要があるものがあります。以下は、GodotでC#に飛び込む際に注意する必要がある最も重要な問題の一覧ですが、疑問がある場合は、公式の issue tracker for Mono issues <https://github.com/godotengine/godot/labels/topic%3Amono> もご覧ください。

  • エディタプラグインの作成は可能ですが、現在は非常に複雑です。

  • 現在、エクスポートされた変数を除き、状態(State)は保存およびホットリロード時に復元されません。

  • アタッチされた C#スクリプトは、ファイル名と一致するクラス名を持つクラスを参照する必要があります。

  • Godot の snake_case API 命名規則に依存する Get()/Set()Call()/CallDeferred() 及びシグナル接続メソッド Connect() などのメソッドがあります。したがって、例えば CallDeferred("AddChild") を使用する場合、APIは本来の snake_case バージョンである add_child``を期待しているため、\ ``AddChild では動作しません。ただし、任意のカスタムプロパティまたはカスタムメソッドはこの制限なしに使用できます。

Exporting Mono projects is supported for desktop platforms (Linux, Windows and macOS), Android, HTML5, and iOS. The only platform not supported yet is UWP.

GodotにおけるC#のパフォーマンス

いくつかの予備的な ベンチマーク <https://github.com/cart/godot3-bunnymark> によると、一般的にGodot のC#のパフォーマンスはGDScriptと同程度ですが、いくつかの単純なケースではGDScriptの約 ~4倍 です。C++はさらにもう少し高速です。具体的な内容はユースケースによって異なります。GDScriptは、ほとんどの一般的なスクリプトワークロードに対して十分に高速である可能性があります。C#そのものは高速ですが、Godotと通信するときに負荷の高い形式変換処理が必要です。

GodotでのNuGetパッケージの使用

NuGet <https://www.nuget.org/> パッケージは、他のC#プロジェクトと同様に、Godotでインストールおよび使用できます。多くのIDEは、パッケージを直接追加できます。プロジェクトのルートにある .csproj ファイルにパッケージ参照を追加することにより、手動で追加することもできます:

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

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

C#コードのプロファイリング

  • Mono log profiler はLinuxおよびmacOSで利用可能です。Monoの変更により、現在Windowsでは機能しません。

  • こちら<https://github.com/godotengine/godot/pull/34382> _ で説明されている方法で、JetBrains dotTrace <https://www.jetbrains.com/profiler/> _ のような外部のMonoプロファイラーを使用できます。