今天写代码的时候发现了一个问题:
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>();
}
}