[Unity] TryGetComponent

jh Seo·2022년 9월 14일
1

유니티

목록 보기
17/42

개요

함수의 원형

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버전부터 추가되었으므로 그 이전 버전에선 사용할 수 없다.

생각

확실히 trygetcomponent함수가 인자로 넣은 컴퍼넌트에 할당되서 나오므로 작성하기도 편하고
가독성도 좋은 것 같다.

가비지 컬렉션까지 잡아준다니 자주 사용해봐야겠다.

레퍼런스

링크

profile
코딩 창고!

0개의 댓글