Component by Transform

유니티에서 Transform으로 컴포넌트를 얻어올수 있을까?

유니티에서 Transform 컴포넌트를 사용해서 다른 컴포넌트(Component)를 직접적으로 얻어올 수는 없다.
컴포넌트를 얻어오는 것은 일반적으로 GameObject 클래스의 메서드를 사용한다. Transform 컴포넌트는 해당 게임 오브젝트의 위치(position), 회전(rotation), 크기(scale) 정보를 관리하는 역할을 한다.

Rigidbody rb = transform.GetComponent<Rigidbody>();

여기서 transform은 해당 스크립트가 붙어있는 게임 오브젝트의 Transform 컴포넌트이며, transform.GetComponent<T>()는 실제로는 transform.gameObject.GetComponent<T>()의 축약형처럼 작동한다.

🔗 Transform에서 GameObject 얻기
Transform 컴포넌트 클래스는 **gameObject**라는 공개 속성(Public Property)을 가지고 있다.

아래와 같이 GameObject를 얻어 올수 있다.

// 현재 스크립트가 붙어있는 오브젝트의 Transform을 통해 GameObject를 얻어온다.
GameObject myObject = transform.gameObject;

// 예시: 얻어낸 GameObject를 비활성화(Disable) 한다.
myObject.SetActive(false);


GetComponent<T>( )가 유효한지 체크 하는 방법은 2가지가 있다.

1. null 체크

EnemyAction enemyAction = myObject.GetComponent<EnemyAction>();
if (enemyAction != null)
{
    // 컴포넌트가 존재할 때 실행할 코드
}

2. TryGetComponent<T>() 사용 (성능 최적화)
유니티 2019.2 버전부터 추가된 메서드로, 성능 면에서 더 효율적이며 코드도 깔끔하다.

if (myObject.TryGetComponent<EnemyAction>(out EnemyAction enemyAction))
{
    // 컴포넌트가 존재함 (enemyAction 변수에 이미 할당됨)
    enemyAction.DoSomething();
}