【问题标题】:Find all the children gameObjects from the parent gameObject and assign it to a var gameObject?从父游戏对象中找到所有子游戏对象并将其分配给一个var gameObject?
【发布时间】:2019-06-27 13:40:39
【问题描述】:

如何找到父级的所有子级游戏对象(子包括:父-子-子级..)并将其分配给一个游戏对象?

下面的脚本找到了他们当前父母的所有孩子游戏对象,但没有找到找到的孩子的子孩子游戏对象。

public GameObject parent;
private GameObject AssignedChild;

 foreach (Transform eachChild in parent.transform)
        {
            if (eachChild.gameObject.tag == "TagOfTheObject")
            {
               //assign the tagged GameObject to "AssignedChild" GameObject
               AssignedChild = eachChild.gameObject;
            }

        }

【问题讨论】:

  • 可能是递归方法的好时机。看看这篇文章 (stackoverflow.com/questions/25304000/…)
  • 另外,GameObject 字段包含一个 single 对象,如果要存储 所有 个对象,则需要一个数组或列表.
  • @Draco18s 不,我只想找到单个游戏对象,因为我为每个对象分配唯一标签,然后将每个标签分配给每个游戏对象。
  • assign them to gameObject “them”是复数名词。但是如果每个对象都有一个唯一的标签,GameObject.FindWithTag()?
  • 对不起,我更正了,分配不是问题。寻找子和子子游戏对象是问题所在。我的层次结构是“父-子-子-子-等”

标签: c# unity3d


【解决方案1】:

我只需添加一行即可找到所有子游戏对象

public GameObject parent;
private GameObject AssignedChild;

 foreach (Transform eachChild in parent.GetComponentsInChildren<Transform>())
        {
            if (eachChild.gameObject.tag == "TagOfTheObject")
            {
               //assign the tagged GameObject to "AssignedChild" GameObject
               AssignedChild = eachChild.gameObject;
            }

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多