英文:
Does unity have a way to get shallow nested GameObjects
问题
我有一个 WallsContainer(父)游戏对象,其中包含许多(子)Walls 游戏对象。
容器上附加了一个脚本来监听事件,然后检查所有的墙。根据互联网上的信息,目前我有以下代码:
foreach (Transform transform in gameObject.transform)
{
GameObject wall = transform.gameObject;
// 对 wall 进行一些逻辑处理...
}
这个方法似乎有点不太优雅。我理解一切都有一个 transform 的逻辑,但在代码中阅读起来不太好。
我不需要深度递归搜索。我只想获取容器下面的对象。是否有其他解决方案,或者这是我能得到的最好的方法?
英文:
I have a WallsContainer (parent) GameObject that has many (child) Walls GameObjects in it.
The container has a script attached to it to listen to an event and then check all of the walls. Currently based on the internet I have:
foreach (Transform transform in gameObject.transform)
{
GameObject wall = transform.gameObject;
// Some Logic with wall...
}
This just seems hacky. I understand the logic that everything has a transform. It just does not read well in the code.
I do not need a deep recursive search. I just want to get the objects under my container. Is there any other solution or is this the best I get.
答案1
得分: 2
List<Transform> transList = new();
GetComponentsInChildren(true, transList);
for (var trans in transList)
...
或者像这样
for (var trans in GetComponentsInChildren<Transform>(true))
...
英文:
You can use GetComponentsInChildren
List<Transform> transList = new();
GetComponentsInChildren(true, transList);
for (var trans in transList)
...
or like this
for (var trans in GetComponentsInChildren<Transform>(true))
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论