【Unity】从父对象中获取子对象组件的方式

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gamer_君莫愁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值