Unity是否有一种获取浅层嵌套的GameObject的方法?

huangapple go评论85阅读模式
英文:

Does unity have a way to get shallow nested GameObjects

问题

我有一个 WallsContainer(父)游戏对象,其中包含许多(子)Walls 游戏对象。

容器上附加了一个脚本来监听事件,然后检查所有的墙。根据互联网上的信息,目前我有以下代码:

  1. foreach (Transform transform in gameObject.transform)
  2. {
  3. GameObject wall = transform.gameObject;
  4. // 对 wall 进行一些逻辑处理...
  5. }

这个方法似乎有点不太优雅。我理解一切都有一个 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:

  1. foreach (Transform transform in gameObject.transform)
  2. {
  3. GameObject wall = transform.gameObject;
  4. // Some Logic with wall...
  5. }

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

你可以使用GetComponentsInChildren

  1. List<Transform> transList = new();
  2. GetComponentsInChildren(true, transList);
  3. for (var trans in transList)
  4. ...

或者像这样

  1. for (var trans in GetComponentsInChildren<Transform>(true))
  2. ...
英文:

You can use GetComponentsInChildren

  1. List&lt;Transform&gt; transList = new();
  2. GetComponentsInChildren(true, transList);
  3. for (var trans in transList)
  4. ...

or like this

  1. for (var trans in GetComponentsInChildren&lt;Transform&gt;(true))
  2. ...

huangapple
  • 本文由 发表于 2023年7月6日 12:15:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定