How to create a Callable of a delegate/action/func in C#?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Eperson

I want to create a Modal in Godot using C#. Then I decided to create a Singleton of it, because it will be used by all the project and then to call this Modal, you need to pass actions to be assigned to the modal buttons.

I achieved something like that:

public void Alert(
		string title,
		string message,
		List<OptionButton> optionButtons
	)
	{
        Show();
        Title.Text = title;
        Message.Text = message;
        for (int i = 0; i < Buttons.Length; i++)
        {
            if (i < optionButtons.Count)
            {
                Buttons[i].Text = optionButtons[i].Text;
                Buttons[i].TooltipText = optionButtons[i].Tooltip;
                Action callback = optionButtons[i].Action;
                Buttons[i].Connect(
                    "pressed",
                    new Callable(this, nameof(callback))
                );
            }
            else
            {
                Buttons[i].Hide();
            }
        }
    }

The problem is that the “callback” variable is an anonymous function, and not a class function. Is there a way to solve this?

:bust_in_silhouette: Reply From: suribe

You can use the Callable.From function:

            Action callback = optionButtons[i].Action;
            Buttons[i].Connect(
                "pressed",
                Callable.From(callback)
            );

Or even directly, of course:

            Buttons[i].Connect(
                "pressed",
                Callable.From(optionButtons[i].Action)
            );

Thank you!!! It worked!

Eperson | 2022-12-27 19:12