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];
}
}