- Home /
Array copy
If I assign an array to another, both always keeps the same values. So what is the best way to copy the values from one array to another and still keep the arrays independent? (I know I can assign each element separately, but would this be the most efficient way?)
var first : int[] = new int[1];
var second : int[] = new int[1];
function Start ()
{
first[0] = 1;
second[0] = 2;
Debug.Log("first:"+first[0]+" second:"+second[0]);
//first:1 second:2
first = second;
Debug.Log("first:"+first[0]+" second:"+second[0]);
//first:2 second:2
first[0] = 1;
Debug.Log("first:"+first[0]+" second:"+second[0]);
//first:1 second:1
//wish I could change the value of the first without affecting the second
}
Answer by Tialkannos · Sep 28, 2011 at 03:13 PM
instead of
first = second;
the best way I could find is
System.Array.Copy(second,first,1);
Answer by yeoldesnake 1 · Sep 27, 2011 at 05:22 PM
You can simply do
first=second;
That way it copies all of the properties of the second array into the first one , including length.
Another redundant way would be a for loop:
var forPointer:int=0;
for(;forPointer<first.length;forPointer++){
first[forPointer=second[forPointer];
}
This would return an error if the first had a bigger length than the second one.
$$anonymous$$y problem is that when I put first = second; the two arrays always keeps the same values, so when change one, the other also changes
with the for loop I can do what I want, but my question is if it is the best way, because my arrays are quite large
but thanks for your answer anyway
There is no reason to set one equal to the other on each frame or whenever you change that one. I cant see the problem really.
In my code I put this line first[0] = 1; but this change the value in the second array too, I think it is because the arrays now have the same reference (I tried to explain with the comments)
I just want to have a copy of an array, so I can compare if one value have changed. But in this way, both always have the same values, then it is useless to compare.