TryGetComponent

조성원·2025년 5월 17일

컴포넌트가 있는지 확인하고 컴포넌트가 있다면 연결, 컴포넌트가 없다면 false를 반환한다.
GetComponent는 컴포넌트가 없으면 NullReference를 발생시키는 것과 달리 안전하게 컴포넌트를 가져올 수 있다.

public bool TryGetComponent<t>(out T component) where T : Component;

TryGetComponent로 T타입의 컴포넌트를 찾았다면 component 변수에 저장한다. T타입은 반드시 컴포넌트여야 한다.(where)

  • 예시
using UnityEngine;

public class ExampleScript : MonoBehaviour
{
	private Rigidbody rb;
    
    
    private void Start()
    {
        if (TryGetComponent<Rigidbody>(out rb)) // 게임 오브젝트에 Rigidbody 컴포넌트가 있는지 확인하고 가져온다.
        {
            rb.AddForce(Vector3.up * 100f);
        }
        else Debug.Log("Rigidbody component not found.");
    }
}
profile
direction *= -1;

0개의 댓글