问题
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