Unity关于父物体判断子物体下面为空的代码

通过计算该对象身上有多少个子对象来判断该对象是否有子对象,但需要主意的是,gameObj本身也会被记录到Length之中,所以在判断gameObj对象是否有子对象时,应做如下书写(而不是写成==0);
void Start () {
if (GetComponentsInChildren<Transform>(true).Length <= 1)


{
Debug.Log("<color=red>啥也没有</color>");
}


else
{
foreach (Transform child in transform)


{
Debug.Log("<color=green>存在子物体</color>" + child.name);
if (child.name == "Sphere")
{
child.GetComponent<Renderer>().material.color = Color.yellow;
Debug.Log("有子物体萌萌哒");
}
else
{
child.GetComponent<Renderer>().material.color = Color.red;
}
}
}
}

代码转载https://tieba.baidu.com/p/6326766993?red_tag=3013601229

posted @ 2020-06-24 14:56  北特  阅读(1278)  评论(0编辑  收藏  举报