运用递归查找对象下的所有子物体

来源:互联网 发布:知乎删除答案 编辑:程序博客网 时间:2024/05/19 06:37

最近,创建了好多对象,突然想知道我到底创建了多少对象,于是。。。。

1.ctrl+a,然后alt+右方向键,使所有物体呈展开状态,然后执行代码

 Debug.Log(Selection.gameObjects.Length);

嗯,就是这样,一句话的事,但是。。。觉得不够方便(自己作死)于是有了2
2.还是一句话的事。。。

 Debug.Log(FindObjectsOfType<Transform>().Length);

嗯。。。好像总觉得哪里少点,这个是查找全局活动的transform组件,由于每个对象都必须有且只能有一个transform,所以还是可行的,但是我想知道指定的对象有多少子物体怎么办,于是有了3
3.那就层层查找吧,找到一个累加1,一直累加

 GameObject game = Selection.activeGameObject;            for (int i = 0; i < game.transform.childCount; i++)            {                a++;                for (int j = 0; j < game.transform.GetChild(i).childCount; j++)                {                    a++;                    for (int k = 0; k < game.transform.GetChild(i).GetChild(j).childCount; k++)                    {                        a++;                        for (int n = 0; n < game.transform.GetChild(i).GetChild(j).GetChild(k).childCount; n++)                        {                            a++;                        }                    }                }            }            Debug.Log(a);

这。。。好像只能查找四级啊,再深了就找不到了。。。而且这也不是程序员做的事啊这个。。。。
4.想到了递归?

  public void FindGame(Transform t)    {        Transform[] trans = FindChild(t);        if (trans == null)            return;        for (int i = 0; i < trans.Length; i++)        {            FindGame(trans[i]);        }    }    public int a;    public Transform[] FindChild(Transform t)    {        Transform[] trans = new Transform[t.childCount];        if (t.childCount > 0)        {            for (int i = 0; i < t.childCount; i++)            {                a++;                trans[i] = t.GetChild(i);            }            return trans;        }        else            return null;    }

嗯。。最后才想到了递归,反射hu有点。。。
不过问题总算解决了,如果有其他解决方案还请指教。虽然只是一个简单的,很无聊的需求。。。。

阅读全文
0 0
原创粉丝点击