- Home /
How to combine Vector3 arrays?
Here is an example in JS:
var vArray:Vector3[]; var positions:Vector3[];
function AddToArray(){ //Add positions to the vArray. }
How would I combine two arrays like this? A single array out of two arrays.
Any hint is very much appreciated.
Answer by Eric5h5 · Apr 18, 2011 at 09:23 PM
You can use System.Array.Copy:
function CombineVector3Arrays (array1 : Vector3[], array2 : Vector3[]) : Vector3[] {
var array3 = new Vector3[array1.length + array2.length];
System.Array.Copy (array1, array3, array1.length);
System.Array.Copy (array2, 0, array3, array1.length, array2.length);
return array3;
}
Well, it's a bit shorter than my first solution and i guess a bit more efficient than my second ;) Does System.Array.Copy even care about the containing type or is it blind (object) copying?
@Bunny83: http://msdn.microsoft.com/en-us/library/system.arraytypemismatchexception.aspx Aside from being shorter, System.Array.Copy is a little more efficient than doing it yourself.
Answer by Bunny83 · Apr 18, 2011 at 08:49 PM
Arrays can't be resized so you have to create a new array that is big enough to hold the elements of both arrays.
var vArray:Vector3[]; var positions:Vector3[];
function AddToArray(){ var tmpArray = new Vector3[vArray.length + positions.length]; var i = 0; for (var V : Vector3 in vArray) { tmpArray[i++] = V; } for (var V : Vector3 in positions) { tmpArray[i++] = V; } vArray = tmpArray; }
But with a List it would be simpler
var vArray:Vector3[]; var positions:Vector3[];
function AddToArray(){ var tmpArray = new List.<Vector3>(vArray); tmpArray.AddRange(positions); vArray = tmpArray.ToArray(); }
Answer by Wibbs 1 · Apr 18, 2011 at 08:29 PM
I'm not at my home computer so can't check whether this exactly right, but it should give you an idea...
var i:int;
for (i=0; i<vArray.Count; i++) { vArray[i] += positions[i]; }
If += doesn't work then change the line to:
vArray[i] = vArray[i] + positions[i];
Thank you. I've tried your first suggestion it I get the this error: NullReferenceException.
And your second suggestion will add values. What i'm after is to make a single array out of two.
Your answer
Follow this Question
Related Questions
Getting Vector3 from random item in List 1 Answer
A node in a childnode? 1 Answer
How to prevent picking the same combination in array? 1 Answer
Create an array of Vector3 from Editor script 1 Answer
Get size of a vector3 array c# 1 Answer