- Home /
Question by
Teiwaz · Jul 03, 2013 at 12:25 PM ·
nullreferenceexception
Why! I dont get it!NullReferenceException: Object reference not set to an instance of an object
Hey folks, googles about 1H on this. Still no Solution (or iam asking the oracle wrong). So i have this class:
public class CompMatrix : MonoBehaviour {
public int[] top;
public int[] left;
public int[] right;
public int[] bot;
public enum direction {LEFT,RIGHT,TURN}
public void createFullMatrix() {
top = new int[3] {1,1,1};
right = new int[3] {1,1,1};
bot = new int[3] {1,1,1};
left = new int[3] {1,1,1};
}
...
}
Now i try to initilize this with this:
...
public CompMatrix[,] compLevel;
...
void Start(){
compLevel = new CompMatrix[maxLevelSizeX, maxLevelSizeZ];
}
And Use it here:
void createCompatMatrix(){
for(int x=0; x < maxLevelSizeX; x++) {
for(int z=0; z < maxLevelSizeZ; z++) {
compLevel[x,z].createFullMatrix();
}
}
}
Butif i try this i just getting:
!!!!!!!NullReferenceException: Object reference not set to an instance of an object!!!!!!
Seams i need to do somthing else but i dont know what ! Can some one please turn on the light for me ?
greetings Teiwaz
Comment
Best Answer
Answer by Seregon · Jul 03, 2013 at 01:20 PM
Initialising an array of items doesn't actually initialise an item in each index, it only allocates the memory for the overall array. To solve this, initialise each individual item before using it, something like this:
void createCompatMatrix(){
for(int x=0; x < maxLevelSizeX; x++) {
for(int z=0; z < maxLevelSizeZ; z++) {
compLevel[x,z] = new CompMatrix();
compLevel[x,z].createFullMatrix();
}
}
}
Your answer
