게임 프로그래밍/C# & Unity 관련 자료

[Unity]NullReferenceException: Object reference not set to an instance of an object

Dannian 2017. 9. 20. 16:09
반응형

GameObject 를 Instantiate 한 후.. 그 안에서 Script component 를 얻어왔다. 

이런식으로..

DynamicWorldSegment p_ws = (DynamicWorldSegment)p.GetComponentInChildren<DynamicWorldSegment>();

 

그리고 그안에 정의된 초기화 함수를 호출 했는데..

NullReferenceException: Object reference not set to an instance of an object !!!!!

요런 에러가 발생 했다...

 

계속 이유를 파다 보니..

클래스 맴버변수의 초기화 가 문제였다..

변수 선언부에 

  public System.Collections.Generic.List<DynamicMapJoint> listJoint = new System.Collections.Generic.List<DynamicMapJoint>();

  요런식으로 선언해두었던 변수들의 초기화는 Start 함수가 호출되는 시점이 되어야만 할당 되는걸 알았다. 

 

그래서 바꾼 방식은..

 public System.Collections.Generic.List<DynamicMapJoint> listJoint = null; 

 요렇게 선언만 해 두고 

 별도로 만든 초기화 함수안에다가 new 할당 코드를 넣어줌으로 해결 했다. 

    listJoint = new System.Collections.Generic.List<DynamicMapJoint>();

 

 

 

관련 링크 - http://blog.daum.net/_blog/BlogTypeView.do?blogid=0S1ol&articleno=50

 

 

Dannian의 블로그입니다.

 

 

 

 

퍼가실때는 댓글 한 번씩 달아주세요!

 

Per Aspera ad Astra!

 

 

반응형