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

半腔热情 提交于 2020-01-06 19:38:33

问题


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:


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

In the second testcase only the first script returns the object, the second script returns null



来源:https://stackoverflow.com/questions/34151721/unity-finding-childs-transform-component-vs-traversing-parents-transform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!