代码之家  ›  专栏  ›  技术社区  ›  Daniel

在子对象中查找所有包含实现接口的脚本的对象

  •  0
  • Daniel  · 技术社区  · 4 年前

    假设我有一个GameObject A 有很多孩子 a1 , a2 , ..., an .

    如何查找的某些子级实现的接口的列表 A. ?


    我试着适应 glitcher's answer from here 但当我执行时,我得到了一个堆栈溢出。

    public static List<T> FindObjectsWithInterfaceInChildren<T>(this GameObject root)
    {
        List<T> interfaces = new List<T>();
        T[] childrenInterfaces = root.GetComponentsInChildren<T>();
        foreach (var childInterface in childrenInterfaces) interfaces.Add(childInterface);
        return interfaces;
    }
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   derHugo    4 年前

    这种扩展方法没有任何意义。

    它基本上只是返回

    return root.GetComponentsInChildren<T>().ToList();
    

    return new List<T>(root.GetComponentsInChildren<T>());
    

    因此,如果你真的需要将其作为列表,你也可以直接使用其中一个。

    阿法伊克 GetComponentsInChildren 实际上是不久前更改的 现在应该可以很好地用于接口 .=>这已经是你问题的答案了。

    此外,我会输入“true”来查找不活跃和残疾的儿童


    总的来说,请注意 GetComponentsInChildren 包括连接到的组件 root 对象本身。


    您引用的链接是为了查找 所有 中某个接口的对象 整个场景 并且类似于例如。

    public static T[] FindObjectssOfTypeAll<T>(bool includeInactiveAndDisabled)
    {
        var output = new List<T>();
        // Go through all scenes
        for(var i = 0; i < SceneManager.sceneCount; i++)
        {
            var scene = SceneManager.GetSceneAt(i);
    
            // Go through all root objects
            foreach(var root in scene.GetRootGameObjects)
            {
                // get all children
                output.AddRange(root.GetComponentsInChildren(includeInactiveAndDisabled));
            }
        }
        // Consider rather returning "List<T>" and skip the "ToArray"
        return output.ToArray();
    }