You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C#中获取Godot特定类型子节点并返回Godot.Collections.Array的问题

在Godot C#中获取特定类型子节点并返回Godot.Collections.Array的正确方法

问题核心

你遇到的问题源于对Godot.Collections.Array和System.Array的混淆,以及对Godot数组泛型支持的不明确:

  • 旧版Godot(3.x)的Godot.Collections.Array是非泛型类型,无法使用<T>形式的类型参数
  • 未指定命名空间时,代码中的Array会默认指向System.Array,导致类型匹配冲突

你的两次尝试错误原因

  1. 第一次尝试:
    你使用了Array<T>,但无论是Godot.Collections.Array(旧版)还是System.Array都是非泛型类型,不支持添加类型参数,因此触发“非泛型类型‘Array’不能与类型参数一起使用”的错误。

  2. 第二次尝试:

    • 返回类型Array默认对应System.Array,和你实际要返回的Godot.Collections.Array类型不兼容,导致转换错误
    • 代码最后错误返回了原始的foundNodes(未筛选的所有子节点),而非筛选后的results,属于逻辑错误

正确实现方案

针对Godot 3.x(非泛型Array)

可以通过两种方式实现:

方式1:遍历筛选
using Godot;

public static class NodeHelper
{
    public static Godot.Collections.Array GetChildrenOfType<T>(Node node) where T : Node
    {
        var filteredChildren = new Godot.Collections.Array();
        foreach (Node child in node.GetChildren())
        {
            if (child is T typedChild)
            {
                filteredChildren.Add(typedChild);
            }
        }
        return filteredChildren;
    }
}
方式2:结合Linq转换
using Godot;
using System.Linq;

public static class NodeHelper
{
    public static Godot.Collections.Array GetChildrenOfType<T>(Node node) where T : Node
    {
        // 先用Linq筛选指定类型,再转换为Godot数组
        var systemArray = node.GetChildren().OfType<T>().ToArray();
        return new Godot.Collections.Array(systemArray);
    }
}

针对Godot 4.x(支持泛型Array)

Godot 4.x的Godot.Collections.Array已支持泛型,可以直接返回泛型数组:

using Godot;
using System.Linq;

public static class NodeHelper
{
    public static Godot.Collections.Array<T> GetChildrenOfType<T>(Node node) where T : Node
    {
        return new Godot.Collections.Array<T>(node.GetChildren().OfType<T>());
    }
}

使用示例

在任意节点脚本中调用:

var buttonChildren = NodeHelper.GetChildrenOfType<Button>(this);
foreach (Button btn in buttonChildren)
{
    // 处理按钮节点逻辑
}

内容的提问来源于stack exchange,提问作者amir mola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:42:54