내일배움캠프 21일차 TIL - GetComponentInChildren

권태하·2024년 5월 14일
post-thumbnail

스크립트가 부착된 오브젝트의 자식 오브젝트에 있는 컴포넌트를 가지고 오기 위해
GetComponentInChildren을 사용했다.
처음에 GetComponent로 했을 때는 오류 메세지 발생!

MissingComponentException: There is no 'Animator' attached to the "Player" game object, but a script is trying to access it.

public class AnimationController : MonoBehaviour
{
    protected Animator animator;
    protected TopDownController controller;

    protected virtual void Awake()
    {
        animator = GetComponentInChildren<Animator>();
        controller = GetComponentInChildren<TopDownController>();
    }
}
public class CharacterAnimationController : AnimationController
{
    private static readonly int isRun = Animator.StringToHash("isRun");

    // 문턱 - Threshold
    private readonly float magnitudeThreshold = 0.5f; 

    protected override void Awake()
    {
        base.Awake();
    }

    void Start()
    {
        controller.OnMoveEvent += Move;
    }

    private void Move(Vector2 direction)
    {
        animator.SetBool(isRun, direction.magnitude > magnitudeThreshold);
    }
}
profile
스터디 로그

0개의 댓글