Skip to content

[Instantiable]: Add support for generic Init/New methods. #203

Description

@willnationsdev

If I want to define an [Instantiable] type that can be "instantiated" from GDScript with potentially multiple single-parameter overrides, I can't quite do that properly in C# at the moment.

[Instantiable("Init", "CreateFromTime"]
public partial class Clock : Control
{
    private int _time;

    public void Init<[MustBeVariant] T>(T value)
    {
        int time = 0;
        if (value is int i)
        {
            time = i;
        }
        else if (value is string format)
        {
            if (TimeSpan.TryParse(format, out var timeSpan))
            {
                time = (int)timeSpan.TotalSeconds;
            }
            else
            {
                GD.PushError($"Invalid time format '{format}'");
            }
        }
        if (time > 0)
        {
            _time = time;
        }
        else
        {
            GD.PushError($"'int' or 'string' must be provided to Init<T> method, but got '{typeof(T)}'");
        }
    }
}

Resulting generated output currently:

    // The `T` here is never declared as a generic parameter anywhere, so it produces an error.
    public static Clock CreateFromTime(T value)
    {
        var scene = (Clock)_Clock.Instantiate();
        scene.Init(value);
        return scene;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions