Get all children of a Godot Node with specific type in C#

1.1k views Asked by At

I need to find all children of a Godot node with specific type in C# and return them as Godot.Collections.Array. But it seems using Generics with Array is not possible(or maybe I don't know how to do it). Here is two attempts I did both not working:

1:

public static Array<T> GetChildren<T>(Node _node) where T : Node
    {
        return _node.GetChildren().Where(x => x is T).ToArray();
    }

which results in this error: "The non-generic type 'Array' cannot be used with type arguments" 2:

public static Array GetChildren<T>(Node _node) where T : Node
    {
        var foundNodes = _node.GetChildren();
        var results = new Godot.Collections.Array();
        foreach (var nd in foundNodes)
            if (nd is T) results.Add(nd as T);
        return foundNodes;
    }

which gives me this error: "Cannot implicitly convert type 'Godot.Collections.Array<Godot.Node>' to 'System.Array'"

1

There are 1 answers

2
amir mola On

I found a way to do it:

public static Variant GetChildren<T>(Node _node) where T : Node
    {
        return _node.GetChildren().Where(x => x is T).ToArray();
    }

I used "Variant" as the function type but the downside is I have to cast the result every time I use it. like this:

Results = (Array<NodeType>)GetChildren<NodeType>(this);

So I'm not sure if there's still a better solution.