Error: Null Reference Exception
I have an error in my Array, but i couldnt figure out why it was null. What am I doing wrong?
Error NullReferenceException: Object reference not set to an instance of an object
The object that i have placed in Scroller, has 4 child game objects (planes) under it. The error states that its a problem with where I am setting the values of the levels array;
please help!
using System;
[Serializable]
public class Levels
{
public GameObject levelImage;
public GameObject locked;
public bool isLocked;
}
public class LevelSelectMenu : MonoBehaviour {
public GameObject scroller;
public Levels[] levels;
void Awake ()
{
if (scroller && levels.Length == 0)
{
int children = scroller.transform.childCount;
print (children);
levels = new Levels[children];
for (int i = 0; i < children; i++ )
{
levels[i].levelImage = scroller.transform.GetChild(i).gameObject;
levels[i].locked = levels[i].levelImage.transform.GetChild(i).gameObject;
levels[i].isLocked = GlobalState.levelStats[i].locked;
}
}
}
}
please ignore the line with the globalstate in it
Answer by bubzy · Nov 13, 2015 at 11:41 PM
you kinda gotta do that differently.
levels = new Levels[children];
wont work as this does not correctly initialize the array
for(int i = 0; i < children; i++)
{
levels[i] = new Levels();
}
this will correctly initialize the array for you.
oh my god. i feel so stupid. Working all day i had a brain fart. thank you very much, i will try it
Your answer

Follow this Question
Related Questions
#Need Fast Help# NullReferenceException: Object reference not set to an instance of an object 0 Answers
Hi there i need a little help please with in app purchase script 0 Answers
NullReferenceException when attempting to call a GameObject from within PointerEventData 1 Answer
getcomponent cant find every button script in every gameobject 1 Answer
How Can I Create My Own Textures? 3 Answers