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

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

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>();
    }
}

猜你喜欢

转载自blog.csdn.net/BAID_maomingyang/article/details/128436300
今日推荐