- Home /
Can't build a Vector3 array
TLDR: Anyone have a working solution for inserting Vector3's into an array?
Hello friends, I'm trying to build a Vector3 array to store a bunch of locations. I started by simply using
var positions = Vector3[]
However, I soon learned that you can't use .Push or .Add with Vector3 for whatever reason. So I searched and found this solution: [http://answers.unity3d.com/questions/60191/arraypush-for-vector3-or-how-to-add-items-to-vecto.html][1]
So I tried using his first sample code:
import System.Collections.Generic;
var positions = List.();
function AddItem (var item : Vector3) {
positions.Add(item);
}
However, Unity would give errors regarding an "Unexepected token" for the period on var positions = List.();
. I tried to remove the period, and got this error: BCE0157: Generic types without all generic parameters defined cannot be instantiated.
Thats about the limit of what I know about List, so I decided to try his next solution.
var positions : Vector3[];
function AddItem (var item : Vector3) : Vector3[] {
var temp : Vector3[] = new Vector3[positions.Length + 1];
temp[temp.Length - 1] = item;
for(var i : int = 0; i < positions.Length; i++) {
temp[i] = positions[i];
}
}
There were no errors on this code, however for whatever reason, this doesn't actually insert data into the positions array! I checked that the item parameter is passing through successfully on AddItem(), and it is. So its just not being stored in the array for whatever reason.
If anyone has a working solution to this, would be much appreciated! Thanks [1]: http://answers.unity3d.com/questions/60191/arraypush-for-vector3-or-how-to-add-items-to-vecto.html125
Answer by Jesus_Freak · Jun 30, 2011 at 08:17 AM
in your first code, just replace positions with:
import System.Collections.Generic;
var positions = List.<Vector3>();
function AddItem(var item : Vector3) {
positions.Add(item);
}
that way, you can keep you var names. and that will work.
Answer by GuyTidhar · Jun 30, 2011 at 08:16 AM
You can use "Array" (http://unity3d.com/support/documentation/ScriptReference/Array.html)
var vectorArray : Array = new Array();
function AddItem(item : Vector3)
{
vectorArray.Add(item);
}
Hi, I think this doesn't work. I'm running another function that will utilize the vectorArray[i] as a parameter. However, the parameter is set to a Vector3 type, and I think this type of array is just an Object type? Unity spits back: "The best overload for the method (..UnityEngine.Vector3)is not compatible with the argument list (..Object). Thanks for your help though!
Array is slow and not statically typed. List is much better.
Your answer
