Can't call C# method from GDscript, anybody Please help

Godot Version

4.2.1

Question

How do I call a C# method from gdscript?

My gdscript code looks something like this:

func _ready():
var thingy = $CsharpUnderlingNode.yummy(2)

C# code:

static string yummy(number){
return number + 15;

}

But I’m getting this error:
Invalid call. nonexistent function ‘yummy’ in base ‘Node2D yummything.cs’.

This is not my actual code but it works the same functionally.

I have no idea how to fix it.

If you can help please let me know.

your gdscript needs a class_name yourClass to be able to access it globally

What does that mean exactly?

at the top of your script add

class_name yourClass where yourClass is the name of your script

Could you provide an example? I don’t quite understand.

c#

using Godot;
using System;
[GlobalClass]
public partial class MyGlobalClass:Node {
	[Export]
	public string MyStringVariable = "Hello, world!";
	[Export]
	public int MyMagicNumber = 7;
}

godot

extends Node
@onready var m_my_global_class_node = $MyGlobalClassNode

func _ready() -> void:
	print("MyStringVariable:", m_my_global_class_node.MyStringVariable);
	print("MyMagicNumber:", m_my_global_class_node.MyMagicNumber);

screen shot

1 Like

You can check the documentation here: GDScript reference — Godot Engine (stable) documentation in English

1 Like