Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

Scripting multi-langage

Godot vous permet de mélanger les langages de script selon vos besoins. Cela signifie qu'un seul projet peut utiliser des nœuds en C# et en GDScript. Cette page passe en revue les interactions possibles entre deux nœuds écrits dans des langages différents.

Les deux scripts suivants serviront de référence tout le long de cette page.

extends Node

var my_property: String = "my gdscript value":
    get:
        return my_property
    set(value):
        my_property = value

signal my_signal
signal my_signal_with_params(msg: String, n: int)

func print_node_name(node: Node) -> void:
    print(node.get_name())

func print_array(arr: Array) -> void:
    for element in arr:
        print(element)

func print_n_times(msg: String, n: int) -> void:
    for i in range(n):
        print(msg)

func my_signal_handler():
    print("The signal handler was called!")

func my_signal_with_params_handler(msg: String, n: int):
    print_n_times(msg, n)

Installer des nœuds

Si vous n'utilisez pas de nœuds venant de l'arbre des scène, vous voudrez probablement instancier les nœuds directement depuis le code.

Instanciation des nœuds C# à partir de GDScript

Utiliser un script en C# depuis GDscript ne demande pas énormément de travail. Une fois chargé (see Les classes comme ressources) le script peut être instancié avec new().

var MyCSharpScript = load("res://Path/To/MyCSharpNode.cs")
var my_csharp_node = MyCSharpScript.new()

Avertissement

Lors de la création de script .cs, vous devriez toujours garder à l'esprit que la classe que Godot va utiliser est celle qui possède le même nom que le fichier .cs . Si cette classe n'existe pas dans le fichier, vous verrez l'erreur suivante : Invalid call. Nonexistent function `new` in base.

Par exemple, MonSuperNoeud.cs devrait contenir une classe nommée MonSuperNoeud.

The C# class needs to derive a Godot class, for example GodotObject. Otherwise, the same error will occur.

Vous devez aussi vérifier que votre fichier .cs est référencé dans le fichier projet .csproj. Sinon la même erreur se produira.

Instanciation des nœuds GDScript à partir de C#

Du côté d'un script C#, tout marche de la même manière. Une fois le script écrit en GDscript chargé depuis le script en C#, il peut être instancié avec GDScript.New().

var myGDScript = GD.Load<GDScript>("res://path/to/my_gd_script.gd");
var myGDScriptNode = (GodotObject)myGDScript.New(); // This is a GodotObject.

Ici, on utilise un Object, mais vous pouvez utiliser la conversion de type tel qu'expliqué dans Conversion de type et Casting.

Accès aux champs

Accès aux champs C# depuis GDScript

Accéder au champ de C# depuis le GDscript est intuitif, vous ne devriez pas rencontrer de problème.

# Output: "my c# value".
print(my_csharp_node.MyProperty)
my_csharp_node.MyProperty = "MY C# VALUE"
# Output: "MY C# VALUE".
print(my_csharp_node.MyProperty)

Accéder au champ de GDscript depuis du C#

As C# is statically typed, accessing GDScript from C# is a bit more convoluted. You will have to use GodotObject.Get() and GodotObject.Set(). The first argument is the name of the field you want to access.

// Output: "my gdscript value".
GD.Print(myGDScriptNode.Get("my_property"));
myGDScriptNode.Set("my_property", "MY GDSCRIPT VALUE");
// Output: "MY GDSCRIPT VALUE".
GD.Print(myGDScriptNode.Get("my_property"));

Keep in mind that when setting a field value you should only use types the GDScript side knows about. Essentially, you want to work with built-in types as described in Types intégrés or classes extending Object.

Méthodes d'appel

Appel de méthodes C# depuis GDScript

Encore une fois, appeler des méthodes C# depuis GDScript devrait être simple. Le processus de sérialisation fera de son mieux pour vous fournir les arguments qui correspondent aux signatures de fonction. Si c'est impossible, vous verrez l'erreur suivante : Invalid call. Nonexistent function `FunctionName`.

# Output: "my_gd_script_node" (or name of node where this code is placed).
my_csharp_node.PrintNodeName(self)
# This line will fail.
# my_csharp_node.PrintNodeName()

# Outputs "Hello there!" twice, once per line.
my_csharp_node.PrintNTimes("Hello there!", 2)

# Output: "a", "b", "c" (one per line).
my_csharp_node.PrintArray(["a", "b", "c"])
# Output: "1", "2", "3"  (one per line).
my_csharp_node.PrintArray([1, 2, 3])

Appel de méthodes GDScript depuis C#

To call GDScript methods from C# you'll need to use GodotObject.Call(). The first argument is the name of the method you want to call. The following arguments will be passed to said method.

// Output: "MyCSharpNode" (or name of node where this code is placed).
myGDScriptNode.Call("print_node_name", this);
// This line will fail silently and won't error out.
// myGDScriptNode.Call("print_node_name");

// Outputs "Hello there!" twice, once per line.
myGDScriptNode.Call("print_n_times", "Hello there!", 2);

string[] arr = ["a", "b", "c"];
// Output: "a", "b", "c" (one per line).
myGDScriptNode.Call("print_array", arr);
// Output: "1", "2", "3"  (one per line).
myGDScriptNode.Call("print_array", new int[] { 1, 2, 3 });
// Note how the type of each array entry does not matter
// as long as it can be handled by the marshaller.

Connecting to signals

Connecting to C# signals from GDScript

Connecting to a C# signal from GDScript is the same as connecting to a signal defined in GDScript:

my_csharp_node.MySignal.connect(my_signal_handler)

my_csharp_node.MySignalWithParams.connect(my_signal_with_params_handler)

Connecting to GDScript signals from C#

Connecting to a GDScript signal from C# only works with the Connect method because no C# static types exist for signals defined by GDScript:

myGDScriptNode.Connect("my_signal", Callable.From(MySignalHandler));

myGDScriptNode.Connect("my_signal_with_params", Callable.From<string, int>(MySignalWithParamsHandler));

Héritage

Un fichier GDScript ne peut pas hériter d'un script C#. De même, un script C# ne peut pas hériter d'un fichier GDScript. En effet, la complexité de la mise en œuvre serait telle que cette limitation ne sera surement pas levée à l'avenir. Voir cette édition de GitHub pour plus d'informations.