5
\$\begingroup\$

I am using Godot Engine 3.0.6 Mono for Windows x64. I am prototyping the majority of my project in C# before I rewrite the game in C++ for release. I installed this plugin mostly to help with testing and debugging value-sensitive functionality. To make this possible however, I will need to be able to make references to my C# classes from GDScript (or vice versa) for binding commands. I could not find any instructions on how to do this in the official documentation. Can this be done currently in either direction?

Note: If the references are made from C# to GDScript classes, I need to be able to cast the Nodes respectively to make function calls.

\$\endgroup\$

1 Answer 1

7
\$\begingroup\$

I figured out how this works both ways after a couple of days.

It is not immediately obvious and the GDScript interpreter will yell at you, but as long as your C# objects are included in the .csproj file and the class itself extends Object, you can call any method in the C# script.

The C# API adds a nice way of calling GDScript instance functions, which is are the Godot.Object methods Call(), CallDeferred(), and Callv().

E.G. given:

SampleGD.gd

func from_csharp(content):
    print(content)

Then in C# you would obtain a reference to this object in the scene or use ResourceLoader to load a new instance. After such, you could do:

SampleCS.cs

var sampleGD = FindNode("SampleGD");
sampleGD.Call("from_csharp", "Hello from C#!");
\$\endgroup\$
2
  • \$\begingroup\$ I'm struggling to find an example of the reverse, SampleGD calling a (new) method of SampleCS. Would you be kind enough to show us an example of bi-directional calling between gdscript and csharp? \$\endgroup\$ Nov 19, 2023 at 0:57
  • \$\begingroup\$ the problem i had was due to operator overloading meaning there was no valid csharp function for the arguments called from gdscript. the type of gdscript arguments likely needs to be specified as GodotObject. public partial class mycsharp : Node2D { public void mymethod(GodotObject arg1){GD.Print("mycsharp:mymethod:arg1=", arg1)}} and gdscript func _ready(): $mycsharp.mymethod(self) seemed to work in one manual test case \$\endgroup\$ Nov 19, 2023 at 1:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .