- Home /
Setting the size of an array inside a class object, not working
I keep getting a "Object reference not set to an instance of an object" error every time I try to define the size of an array, which is located in an array of class objects. Here is an simplified, detached example of what I am trying to accomplish:
var matrixItem : mClass[];
class mClass{
obj : Vector2[];
}
function Awake(){
matrixItem = new mClass[10];
for(i = 0; i < matrixItem.length; i++){
matrixItem[i].obj = new Vector2[64];
}
}
Can anyone help me determine what I am doing wrong? Thank you for any advice!
Answer by Benproductions1 · Sep 17, 2013 at 02:00 AM
Hello,
Your problem is not the creation of the built-in array. It would have been a more simple thing to solve had you posted the actual error (including line number) rather than only quote it.
When you create a new built-in array of non-struct objects, then each element is always going to be null
. So when you create a new mClass[2]
you will get something line [null, null]
. A null
value does not have a obj
field and therefore throws an error.
When using built-in arrays, you need to initialize the elements so that they are not null
:
for (i = 0; i < array.length; i++) {
array[i] = new mClass();
array[i].obj = new Vector2[64];
}
For a Vector2
array however, you do not need to do this because Vector2
is a structure not a class.
Hope this helps,
Benproductions1
Thank you for the input, but I still do not get an array of vectors in each of the array objects. This is what my script snippet currently looks like after using the suggestion you provided:
for(i = 0; i < terrainSet.length; i++){
terrainSet[i] = new array$$anonymous$$atrix();
terrainSet[i].matObj = new Vector2[2048];
for(j = 0; j < terrainSet[i].matObj.length; j++){
terrainSet[i].matObj[j]=Vector2(sData.terrain.sObj[j + ((i-1)*2048)].obj.pos.x, sData.terrain.sObj[j + ((i-1)*2048)].obj.pos.z);
}
}
The interesting thing is that the first object of the "matrix" is returning 2048 vector2 items but the second one isn't: http://puu.sh/4twD$$anonymous$$.png
It works! I'm sorry that was my fault:
[j + ((i-1)*2048)]
//should be
[(i*2048) + j]
Your answer
Follow this Question
Related Questions
Recursive Tree Loop? How do i make the matrix-array? 3 Answers
As I compare 4 objects in an array? 2 Answers
IndexOutOfRangeException: Array index is out of range. 1 Answer
Bigger matrix? 3 Answers
How destroy a object and it's similars 4 Answers