方法1(獲取全部子物體,無(wú)論子物體SetActive是否為true):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public List<GameObject> CH = new List<GameObject>();//儲(chǔ)存物體的列表
// Start is called before the first frame update
void Start()
{
FindChild(this.gameObject);//找到節(jié)點(diǎn)下的所有子物體
}
void FindChild(GameObject child)
{
//利用for循環(huán) 獲取物體下的全部子物體
for (int c = 0; c < child.transform.childCount; c++)
{
//如果子物體下還有子物體 就將子物體傳入進(jìn)行回調(diào)查找 直到物體沒(méi)有子物體為止
if (child.transform.GetChild(c).childCount > 0)
{
FindChild(child.transform.GetChild(c).gameObject);
}
CH.Add(child.transform.GetChild(c).gameObject);
}
}
}
獲取全部子物體后,可通過(guò)list列表對(duì)物體進(jìn)行批處理;
如添加或移除其子物體的組件,判斷其子物體是否有某個(gè)組件等等。
方法二(推薦):文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-544471.html
transform.GetComponentsInChildren<Transform>(); //無(wú)法獲取SetActive為false的子物體
transform.GetComponentsInChildren<Transform>(true); //獲取全部子物體,無(wú)論SetActive是否為true
該方法為Unity內(nèi)置的API,會(huì)查找物體下對(duì)應(yīng)類(lèi)型的全部組件;
(注意:此方法會(huì)查找到本身的Transform)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-544471.html
到了這里,關(guān)于Unity中獲取一個(gè)物體下所有的子物體的方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!