1.GetComponentInChildren
用于獲取對與指定組件或游戲對象的任何子級相同的游戲對象上的組件類型的引用。
該方法在Unity腳本API的聲明格式為:
public T GetComponentInChildren(bool includeInactive = false)
includeInactive參數(可選)表示是否在搜索中包含非活動子游戲對象。
示例用法:
private Image _childImage;private void Awake()
{_childImage = GetComponentInChildren<Image>();
}
要特別注意的是,此方法首先檢查調用它的游戲對象,然后使用深度優先搜索向下遞歸所有子游戲對象,直到找到指定類型的匹配 Component。
因此,如果你要搜索的Component在父對象和子對象都有,那么只會返回父對象的Component。
2.GetComponentsInChildren
用于獲取對與指定組件相同的游戲對象類型的所有組件以及游戲對象的任何子級的引用。(如果父級也有這個組件,那么也會包含在返回值里面)
該方法在Unity腳本API的聲明格式為:
public T[] GetComponentsInChildren(bool includeInactive = false);
includeInactive參數(可選)表示是否在搜索中包含非活動子游戲對象。
示例用法:
using UnityEngine;public class GetComponentsInChildrenExample : MonoBehaviour
{public Image[] images;void Start(){images = GetComponentsInChildren<Image>();}
}
?因此,如果你有一個父對象中只包含一個子對象,父對象和其子對象都有你要搜索的Component,因此第一個方法是解決不了的,怎么辦?
解決方案:用第二個方法,從數組下標1開始訪問(因為數組下標0指向的是父對象的Component的地址)。
using UnityEngine;public class GetComponentsInChildrenExample : MonoBehaviour
{private Image childImage;void Start(){childImage = GetComponentsInChildren<Image>()[1];}
}