Vector3 Arrays in C#

Hi all,

New to Unity and trying to use c# and been struggling for a few hours now trying to create an Array of Vector3 objects.

I’ve seen this question asked alot as I’ve looked round for help, but no matter what advice I try, nothing works.

I dont necessarily need the Array to be dynamic just now, so i can just use a fixed sized array, but for future reference, its really bugging me that i cant get anything (Array, ArrayLists, Lists etc) to work with Vector3.

Thanks for any help!

Paul

The Array class (Javascript relict) or the C# equivalent ArrayList shouldn’t be used at all if possible. They aren’t typesafe and slow (mainly because they aren’t typesafe ;)). It’s still possible to use it, but you have to cast the elements into the right type whenever you want to access an element.

// ArrayList
public ArrayList arrayList = new ArrayList();

arrayList.Add(new Vector3(1,2,3));
Vector3 V = (Vector3)arrayList[0];

It’s better to use native Arrays when you don’t need dynamic arrays or use generic container classes like List / Queue / Stack / Dictionary

// native array
public Vector3[] array = new Vector3[5];

array[0] = new Vector3(1,2,3);
Vector3 V = array[0];

// generic List<Vector3>
public List<Vector3> list = new List<Vector3>();

list.Add(new Vector3(1,2,3));
Vector3 V = list[0];

Keep in mind that C# also supports type inference, so you can use the “var” keyword and let the compiler determine the type. This requires you to assign a value when you declare the variable:

var list = new List<Vector3>();

This is exactly the same as

List<Vector3> list = new List<Vector3>();

Finally don’t forget that Vector3 is a struct, not a class and therefore a value-type whenever you assign a Vector3 you will copy the values of x,y and z.

I think it goes

public Vector3[] name = new Vector3; 

as I do not use C#, it has to be confirmed.