The question is answered, right answer was accepted
Null reference exception in an if statement that checks for it.
I'm trying to make a script for a light switch and it has a bit that looks like this:
public bool start_off = true;
public Light light0;
public Light light1;
public Light light2;
public Light light3;
public Light light4;
private Light[] lights;
void Start ()
{
if (light0 != null)
{
lights[0] = light0;
}
if (light1 != null)
{
lights[1] = light1;
}
if (light2 != null)
{
lights[2] = light2;
}
if (light3 != null)
{
lights[3] = light3;
}
if (light4 != null)
{
lights[4] = light4;
}
//shutting lights off, if they should be off by default
if(start_off == true)
{
for (int i = 0; i < lights.Length; i++)
{
if(lights[i] != null)
{
lights[i].enabled = false;
}
}
}
}
The line where it says lights[0] = light0 throws this error: NullReferenceException: Object reference not set to an instance of an object (wrapper stelemref) object:stelemref (object,intptr,object) SwitchLights.Start () (at Assets/Scripts/Switches/SwitchLights.cs:24)
How do I fix this? The strange part is that light0 is not empty, but assigned in inspector via drag & drop (and i'd like to retain the possibility of dragging and dropping).
Answer by toddisarockstar · Jul 03, 2017 at 09:24 PM
you have to initialize the array and the length before you do anything with it.
void Start (){
lights= new Light[10] ;
But what if the length is dependent on how many of the lights will be filled in inspector?
you can assign any length you want to an array but they are not resizable. If you use a List ins$$anonymous$$d of an array you can resize and make it bigger while adding things along the way.
actually looking at your code you would say:
void Start (){
lights= new Light[5] ;
//now you can do stuff with it
Why din't you JUST used the Array and fileld in the inspector, no need for many independent variables...
At the time I didn't know you can fill arrays in inspector, it seemed to me like it would be a too specific feature for the inspector to have.