- Home /
Array.Push() for Vector3[] or how to add items to Vector3 array without knowing index
How do you add an item (pos) to a Vector3[] array - it seems Array.push() and others do not work on Vector3[]'s
Answer by Peter G · Apr 23, 2011 at 06:34 PM
Push just doesn't work on .Net arrays in general. Your options are either a list or create a new array.
List option:
import System.Collections.Generic;
var positions = List.(); function AddItem (var item : Vector3) { positions.Add(item); }
Resizing the .Net Array (its a pain comparatively):
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]; } }
or
Array.Resize(ref positions, positions.Length + 1);
positions[positions.Length] = item;
If you need a dynamically resized array then you should almost always choose a list. The exception is when you are developing on some platform that doesn't support generics.
Hi, I am using the script to create a list array of booleans in a Editor Script. but I keep getting the error, length is not a member of System.Collections.Generics.List.
Not sure what the import is for at the top of the page but when I remove the import I get the same error just not of systems collections but of another.
Any idea why it does not allow me to use length?
Thank you Eric, why can I not find "List" or "count" documentation in the Unity Scripting references and where could I look this up.
Your answer
Follow this Question
Related Questions
Avoiding instantiating two things in same location? 1 Answer
store instantiated in Array. c# 1 Answer
distance to variable object 1 Answer
How can i get the index of an array[] as int? 0 Answers
Push a Vector3 array 1 Answer