[TIL] OnTriggerEnter2D 이벤트를 자식에서 부모로 전달하기

Dreamer·2024년 12월 3일

1. 오늘 주제

Unity에서 자식 오브젝트의 Collider2D가 트리거 이벤트를 감지하고, 이를 부모 오브젝트에서 처리하려면 다음 방법을 사용할 수 있다.

  • 자식 오브젝트의 OnTriggerEnter2D 이벤트에서 부모의 스크립트를 가져와 메서드를 호출한다.
// 자식 스크립트
void OnTriggerEnter2D(Collider2D other)
{
    ParentScript parentScript = GetComponentInParent<ParentScript>();
    if (parentScript != null)
    {
        parentScript.HandleChildTrigger(other);
    }
}
  • 부모 스크립트에서 자식의 이벤트를 처리할 메서드를 구현한다.
public void HandleChildTrigger(Collider2D collider)
{
    Debug.Log($"Triggered by: {collider.name}");
}
  • 활용 : 자식 오브젝트의 특정 상태를 부모가 통합적으로 관리할 때 유용.
  • 배운것 : GetComponentInParent()를 활용하면 부모-자식 관계에서 데이터를 쉽게 전달할 수 있다.
profile
새로운 시작

0개의 댓글