Calling a method from a string representation in c#

Godot Version

4.3 C#

Question

So my dialogue system in godot is using a json structure like this

{
        "id": 4,
        "text": "Quiet! You mustn't be so careless when speaking of such a one. ",
        "next": 5,
        "speed": [2,1],
        "fontSize": 1,
        "emotion": 0
    },

and I want to be able to include a string in the json like "function": deleteItemFromInventory("Book") or something like that, so that when i return the json to the script, it takes the string and would do something like

var callable = Callable(self, "deleteItemFromInventory")
callable.Call("Book")

I know that the C# implementation of callable doesnt allow for custom methods really, and the use of lambdas is required instead, but i dont know how i would make a lambda with just the function name as a string in that case. Is there something I could do instead ?

You can use Call() from GodotObject to execute any function. Using HasMethod(), you can also check if the method exists prior to calling it (this includes custom functions). Here is an example:

Node n;

if (n.HasMethod("DeleteItemFromInventory"))
	n.Call("DeleteItemFromInventory", "Book");

I’m not sure what the best approach to calling methods with differing parameter lengths is. Perhaps you should wrap all arguments into a Dictionary and define all related functions with only one Dictionary parameter – I don’t know. Maybe a simple set of if-statements for each accepted length of arguments would work?

if (args.Count == 1)
	n.Call(func, args[0]);
if (args.Count == 2)
	n.Call(func, args[0], args[1]);
if (args.Count == 3)
	n.Call(func, args[0], args[1], args[2]);
// ...and so on.

Perhaps you can take inspiration from the way command line arguments are written, interpreted, and utilized?


I hope that helps. Let me know if you have more questions.

1 Like

Wow thank you so much that was exactly what I was looking for. I was planning on using Godot expression but that seemed really messy so I’m glad there was another option ! Thanks a lot!

Each C# class in godot also has a MethodName class that features each method name as a StringName to avoid using a) “constants” and b) the overhead of marshaling strings. For example, the string “DeleteItemFromInventory” becomes MethodName.DeleteItemFromInventory.