Unity finding child's transform component vs t

2019-09-08 15:49发布

so the idea is that I want to get a GameObject with a specific tag, which is a child of a GameObject, using my own method called FindChildWithTag(). Below there are 2 different methods, which I believe, got a similar purpose.

FIRST

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

    return temp;
}

SECOND

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

    return null;
}

But weirdly, while the first one returns null, the second one returns correctly.

Any idea where my fault lies on the first one? Because my mind tell that those 2 method share the same goal.

Thank you.

1条回答
虎瘦雄心在
2楼-- · 2019-09-08 16:09

The main difference between the scripts is, that the second one looks up only to the childrens of the Transform you are searching on. (Depth 1) the first one using GetComponentsInChildren searches in all children even with greater depth's.

In my testcase both are returning the correct object if there is a correctly tagged child enter image description here

In the second testcase only the first script returns the object, the second script returns null enter image description here

查看更多
登录 后发表回答