Unity TryGetComponent

cometrue·2024년 8월 12일

함수의 원형

public bool TryGetComponent(Type type, out Component component);
public bool TryGetComponent(out T component);

bool형의 함수로 해당 타입의 컴포넌트를 찾았다면 true반환, false반환 하는 함수이다.
찾았다면 out되는 component에 해당 타입 컴포넌트를 할당해준다.

예시

using UnityEngine;

public class TryGetComponentExample : MonoBehaviour
{
    void Start()
    {
        if (TryGetComponent(out HingeJoint hinge))
        {
            hinge.useSpring = false;
        }
    }
}

GetComponent와의 차이점

GetComponent는 해당 타입의 컴퍼넌트를 찾지 못했을 때 memory allocation을 발생시켜
Garbage Collection을 야기할 수 있다.

하지만 TryGetComponent는 해당 컴퍼넌트를 찾지 못했을 때 memory allocation이 발생하지 않고 Gabage Collection을 걱정할 필요없다.

TryGetComponent는 유니티 2019.2버전부터 추가되었으므로 그 이전 버전에선 사용할 수 없다.

profile
게임개발자

0개의 댓글