Unity 查找 child 的变换组件 vs 遍历 parent 的变换

Unity finding child's transform component vs traversing parent's transform

所以我的想法是我想得到一个带有特定标签的 GameObject,它是 GameObject 的 child,使用我自己的方法 FindChildWithTag() ].下面有2种不同的方法,我相信它们的目的相似。

第一个

void GameObject FindChildWithTag(string tag)
{
    GameObject temp = GetComponentsInChildren<Transform>().
        Select(x => x.gameObject).
        FirstOrDefault(x => x.tag == tag && x != transform);

    return temp;
}

第二个

void GameObject FindChildWithTag(string tag)
{
    foreach (Transform item in transform)
    {
        if (item.tag == tag)
        {
            return item.gameObject;
        }
    }

    return null;
}

但奇怪的是,第一个 returns 为空,第二个 returns 正确。

知道第一个是我的错吗?因为我认为这两种方法具有相同的目标。

谢谢。

脚本之间的主要区别在于,第二个脚本仅查找您正在搜索的转换的 childrens。 (深度 1)第一个使用 GetComponentsInChildren 搜索所有 children 甚至更深的搜索。

在我的测试用例中,如果有正确标记的 child

,两者都会返回正确的 object

在第二个测试用例中只有第一个脚本returns object,第二个脚本returns null