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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM