Unity使用GetComponentInChildren<>()方法的坑

本文探讨了在Unity中使用GetComponentInChildren方法时遇到的问题及解决方案。作者发现该方法首先检查当前对象而非子对象,导致获取组件错误。通过先获取子对象再调用GetComponent解决了这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天写代码的时候发现了一个问题:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    private SpriteRender weapon;
    
    private void Start()
    {
        weapon = GetComponentInChildren<SpriteRender>();
    }
}

运行时我发现变量的值不对,把变量的访问修饰符改成public才发现问题:GetComponentInChildren<>()方法并没有取子对象的组件,而是取的自身组件。上网一查才发现GetComponentInChildren<>()方法是先遍历自身的组件,再遍历子对象的组件。

所以该如何解决这个问题呢?我们可以先找到要取组件子对象,再对它用GetComponent<>()方法就行了。最终,我把代码改成了这样就解决问题了:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    private SpriteRender weapon;
    
    private void Start()
    {
        weapon = transform.GetChild(0).GetComponentInChildren<SpriteRender>();
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值