通過計算該對象身上有多少個子對象來判斷該對象是否有子對象,但需要主意的是,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;
}
}
}
}