- Home /
2d array.What is the difference between these two?
I have a simple class and create a 2d array to store objects in x,z coordonates:
var classArray : MyClass[,]; var classTest : MyClass
var x : int; var z : int;
function Update() { classArray = new MyClass[4,4]
for(x=0 ; x<4 ; x++) { for(z=0 ; z<4 ; z++) { classArray[x,z] = classTest;
or ////what is the difference betwen these two
classTest = classArray[x,z];
} }
}
I would like to know what is the difference betwen those two examples and what effects do they have. Are these both the same or are these any different.
I came across this in a tutorial and would like to know more about it before I continue instead of blindly copy/pasting everything.
Answer by swyrazik · Jul 11, 2013 at 06:13 PM
In the first case the element of the classArray with indices x,z is given the value of the classTest, which is equal to null because it was never initialized, and in the end of the code execution the classArray will be filled with null elements.
In the second case the classTest variable will be continuously given the value of the element of the classArray with indices x,z, overriding its previous value, and in the end of the code execution the classTest variable will have the value of the last element of the classArray, i.e. a reference to the last MyClass instance of the array (classArray[3,3]).
If this wasn't clear enough, I could try to explain it more.
If i understand correctly :
classArray[1,1] = classTest; classArray[1,2] = classTest; .......... classArray[4,4] = classTest;
but classTest = classArray[4,4];
Am I correct? And if I am in what circumstances could I use each of them? A simple examle would be nice.
Remember: arrays start from index 0! An array with 4 elements will have indices 0,1,2 and 3. So in this case you will have: classArray[0,0] = classTest; classArray[0,1] = classTest; ... classArray[3,3] = classTest;
or in the second case: classTest = classArray[3,3];
You will more often use the first case. For example, when you want to initialize or modify the value of all the elements of the array, like:
for (x = 0; x < 4; x++){
for (z = 0; z < 4; z++){
classTest = new $$anonymous$$yClass(); //Create an instance of $$anonymous$$yClass
classTest.SetId(x*4 + z); //SetId is a function of $$anonymous$$yClass I came up with
//make any additional modifications you want to classTest
classArray[x,z] = classTest; //The element x,z will now be equal to the instance of $$anonymous$$yClass you created, i.e. classTest
}
}
The second case, as you noticed, is equal to just writing classTest = classArray[3,3] therefore the loops are pointless.