更新于:2013.5.18
开始是找了下U3D的SCRIPT手册,发现找不到这玩意。然后在谷歌搜"unity3d get all
child"才找到了答案。很简单的答案,不过挺有意思的,挺好用。
foreach (Transform child in transform)
{
Debug.Log(child.gameObject.name);
}
transform是你所需要找的物体gameobject的transform。这个for循环就相当于遍历了它的子对象,此时你只要做的是将一个个放进个数组里面就行了。想过滤掉一些子物体在循环里面写一下也就OK了。
删除所有子物体的话:
foreach(Transform child in transform){
Destroy(child.gameObject);
}
忘了是什么时候,以前是不可以这样删的,不过现在可以了。
2014.1.3添加:
遍历删除的方法好像是不可以的,还是要将它储存到一个LIST里面一个个去删。貌似有的情况可以有的不可以,很奇怪。 ______________________________
如何获得一个GameObject对象的所有孩子对象各位大虾, 大侠, 请问如何通过c#脚本获得一个GameObject对象的所有孩子对象?
小弟在线等待,多谢多谢^_^
|
|
charlie_hou | 2011-04-10 12:50 | 我查了查Reference 好像的确没有找到这样的接口 我也是一个初学者,也不太明白为什么不可以……
google了一下,看到了这样一个帖子 http://forum./threads/39790-Get-Child-GameObject-(not-Child-Transform)
人家的回复是: Never use gameobjects! It's rare to use gameobjects, use transforms instead! and I gunaratee u with Transform.Parent function, you'll solve it within no time.
|
|
zcycool | 2011-04-11 15:03 | Transform[] allChildren = parent.GetComponentsInChildren<Transform>(); foreach (Transform child in allChildren){ //child.gameObject }
同理,也可以获得所有带Renderer的子对象 Renderer[] allChildren = parent.GetComponentsInChildren<Renderer>(); foreach (Renderer child in allChildren){ //child.gameObject } |
|
|