I’m not sure if I’m just missing something stupid here but when I try to make a copy of a vector and make a change to it the original vector is being edited too. It seems to be passing by reference.
Vector3[] pointsA = new Vector3[4];
pointsA[0] = new Vector3(0, 0, 0);
Vector3[] pointsb;
pointsb = pointsA;
pointsb[0] += new Vector3(0, 2000, 0);
print(pointsA[0]);
Any ideas why this is not passing by value??
Thanks!
Except it actually prints (0, 0, 0). (The original code did anyway.
) Copy and paste the code you posted into a new script in a new project.
–Eric
No… it prints (0,2000,0), like OP suggests.
BUT, it’s not because vectors are being copied by reference.
It’s the Array that’s referenced.
pointsb[0] and pointsa[0] point to the SAME location in memory, because pointsb and pointsa are the same array.
2 Likes
Sorry stripped out to much. I’ve edited the code above. Seems to be because arrays are a reference type. Is there a workaround for this?
Oh… I guess sblandinuk edited it between my reading it and Eric5h5 reading it.
But yeah, it’s the array being referenced.
Explicitly copy/clone the array instead of doing a simple reference assignment. Since arrays support ICloneable, you can call the Clone() function and, since it returns an opaque object type, cast it to the array type that you know it is.
pointsb = pointsA.Clone() as Vector3[];
You could also allocate a new array of the same size and use the Array.Copy() static function or Array.CopyTo() method, but I find that Clone() is shorter, clearer, and (just guessing based on reasons) more efficient, in the situation where you don’t already have an allocated second array from earlier.
2 Likes