- Home /
Question by
sloopernine · Jun 13, 2014 at 07:33 AM ·
c#arraynullreferenceexception
NullReferenceException: Array C#
Hi
I am getting this error "NullReferenceException: Object reference not set to an instance of an object" with this code. And I really cant see what I am doing wrong?
using UnityEngine;
using System.Collections;
public class PrefabLibrary : MonoBehaviour
{
public PrefabSettings[] prefabSettings;
public enum idPrefab
{
Storage,
DefenceTurret,
Engineering,
RecyclePlant,
WaterPlant,
BioDome,
Corridor,
Barracks,
ScienceLab,
LaunchPad,
RocketSilo,
PowerPlant
}
void Start()
{
prefabSettings = new PrefabSettings[30];
prefabSettings[1].obj = null;
}
}
public class PrefabSettings
{
public GameObject obj;
public int id;
}
Comment
Best Answer
Answer by robertbu · Jun 13, 2014 at 07:37 AM
On line 26, you create the space for the array, but each entry of the array is null. You have to initialize each entry of the array to point to a 'PrefabSettings' object. Something like:
for (int i = 0; i < prefabsSettings.Length; i++) {
prefabSettings[i] = new PrefabSettings;
}
Alternately, you could declare PrefabSettings as a struct instead of a class. As a struct, it would be a value type and would be contained in the array (rather than a reference to a class).
Thanks for the quick answer! I changed the class to a struct ins$$anonymous$$d and now it works without any errors