쾌락없는 책임 (공부)/Unity
[Unity] List가 들어있는 클래스에서 Instantitate를 하면 NullReferenceException: Object reference not set to an instance of an object
허스크
2022. 3. 26. 15:54
반응형
스크립트 상황
스크립트 GenomManager에서 Genom클래스를 가지는 오브젝트들을 Instantitate를 하면 계속해서 "NullReferenceException: Object reference not set to an instance of an object" 가 나오는 문제가 있었습니다.
<Genom 스크립트>
public class Genom : MonoBehaviour
{
public List<bool> GenomList;
public void InitGenom(int genomLength)
{
for(int i = 0; i < genomLength; i++)
{
GenomList.Add(Random.value > 0.5f);
}
}
}
<GenomManager 스크립트>
public class GenomManager : MonoBehaviour
{
...
List<Genom> subjects;
void Start()
{
MakeGenoms();
}
private void MakeGenoms()
{
Vector3 position = new Vector3(0, 0, 0);
for(int xPos = 0; xPos < 8; xPos++)
{
position.x = xPos * distanceBetweenObjects;
for(int zPos = 0; zPos < 8; zPos++)
{
subjects.Add(Instantiate(GenomPrefab, position, Quaternion.identity).GetComponent<Genom>());
subjects[subjects.Count - 1].InitGenom(genomLength);
position.z += distanceBetweenObjects;
}
position.z = 0;
}
}
문제 해결 : List 를 제대로 초기화 하자
문제의 원인은 List에 대한 숙련도가 떨어져서 그렇습니다. 두 클래스, GenomManager에는 subjects 리스트가, Genom에는 GenomList가 있는데 이것들을 초기화 하지 않은채 선언만 해줬기 때문입니다.
<GenomManager>
List<List<bool>> dominantGenoms = new List<List<bool>>();
<Genom>
public List<bool> GenomList = new List<bool>();
이런 식으로 new List를 통해서 초기화를 해줘야 NullReferenceException: Object reference not set to an instance of an object 오류가 안나오게 됩니다.
반응형