所以我的想法是要使用我自己的称为FindChildWithTag()的方法获得带有特定标记的GameObject,该标记是GameObject的子代.下面有两种不同的方法,我相信它们具有相似的目的.
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.
第一
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; }但是很奇怪,虽然第一个返回null,但是第二个返回正确.
有人知道我的错在哪里吗?因为我认为这两种方法具有相同的目标.
Any idea where my fault lies on the first one? Because my mind tell that those 2 method share the same goal.
谢谢.
推荐答案脚本之间的主要区别在于,第二个脚本仅查找要搜索的Transform的子代. (深度1)第一个使用GetComponentsInChildren的对象在所有子对象中进行搜索,即使深度更大.
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
在第二个测试用例中,只有第一个脚本返回对象,第二个脚本返回null
In the second testcase only the first script returns the object, the second script returns null
更多推荐
unity查找子项的变换分量与遍历父项的变换
发布评论