unity查找子项的变换分量与遍历父项的变换

编程入门 行业动态 更新时间:2024-10-26 17:34:00
本文介绍了unity查找子项的变换分量与遍历父项的变换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我的想法是要使用我自己的称为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查找子项的变换分量与遍历父项的变换

本文发布于:2023-11-12 01:16:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580096.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   分量   unity

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!