Declare dynamic array of Vector3 elements in javascript

Can someone tell how to declare a dynamically resizable array of Vector3 elements in javascript? I’ve tried

var data  = Vector3[];

and

var data  : Vector3[] = Array();

neither of which work. I’d like to multiply the elements of the array by a scalar, i.e.

var scaled : Vector3 = data[i] * 0.3

which creates a Vector3.

var data = new Array();

If you put Vector3 data in it, then it’s an array of Vector3s.

–Eric

If I try that and then multiply the array element by a scalar as below:

var data  = new Array();
var scaled : Vector3 = data[0] * 0.3;

I get the error:

Operator ‘*’ cannot be used with a left hand side of type ‘Object’ and a right hand side of type ‘float’

Do I need to cast the data array element to Vector3 before multiplying it by the scalar?

Yep, with Unity iPhone (or regular Unity using #pragma strict). With regular Unity and dynamic typing, it’s not necessary.

–Eric

How would I cast data[0] to Vector3 in Unity’s javascript?

I’ve tried

(Vector3)data[0]

and

Vector3(data[0])

and neither work.

If you were casting to something like a Transform, I’d do “(data[0] as Transform)”, but I’m not sure how to do that in one line with value types.

var temp : Vector3 = data[0];
var scaled = temp * 0.3;

–Eric

Right. I tried this too:

(data[0] as Vector3)

but I got the error

  • Vector3 is a value type. The ‘as’ operator can only be used with reference types.

The only way I could get this to work:

(data as Vector3[ ])[0]

And then it always seems to return null after the cast?

  • Ian

UnityScript does not support structs actually. You can use them through corresponding structures but they won’t work otherwise.
As such, you must use struct arrays ie Vector3[ ] in which case it will have static size and if you resize it, basically create a new array and copy the content of the old one

Yes it does. Obviously it’s always been able to use them, and in Unity 3 you can also declare them directly.

–Eric

doesn’t change the fact that AS will never work as cast for value types … neither enum nor structs will work.