본문 바로가기

Unity/Common

Unity - 소소한 팁, Component null check

반응형

보통 null인지 체크할 때는 아래와 같은 코드를 사용합니다.

using UnityEngine;

public class test
{
 public Camera cam;

	// Start is called before the first frame update
	void start()
    {
	 if(cam == null) {Debug.Log("Cam is null"); }

	}

}

하지만 유니티의 컴포넌트 계열은 bool 데이터로 값이 있을 땐 true, 없을 땐(null일 땐) false를 보내도록 만들어져있습니다. 따라서 아래와 같은 형태로 사용할 수 있습니다.

 

using UnityEngine;

public class test
{
 public Camera cam;

	// Start is called before the first frame update
	void start()
    {
	 if(cam){
     Debug.Log("Not Null");
     }else{
     Debug.Log("Null");
     
     }

	}

}

 

아래처럼 사용할 경우 null이라면 카메라를 찾도록 시도할 수도 있습니다.

using UnityEngine;

public class test
{
 public Camera cam;

	// Start is called before the first frame update
	void start()
    {
	 if(!cam) cam = Camera.main;

	}

}
반응형