help understanding and manipulating arrays

hi, I’m having trouble assigning an array and populating it.

Currently I am just tying to populate an array with information from another, but with the aim to learn to use a 2-dimensional array.

At the moment I am just trying to push all my (map1 then map2 ect) values into one long array.

So I have the array :

var myMap1 : Array = [Vector2(1,1), Vector2(2,1), Vector2(3,1), Vector2(4,1), Vector2(5,1), Vector2(6,1), Vector2(7,1)];

and I’m trying to populate : var myMap : Array;

My first question is, what is the difference between :

var myWhat : Array; // i think this makes an array of no length
var myWhat : Array[]; 
var myWhat : Array = []; // i think this makes an array of no length
var myWhat : Array[] = new Array [5]; // i think this makes an array of nulls, length of 5 (5 places)

My second question is , why doesn’t either of these work ?

for (i=0; i < myMap1.length; i++) {
	myMap _= myMap1*;*_

myWeight = myWeight1*;*
* }*
* for (i=0; i < myMap1.length; i++) {*
_ myMap.Push(myMap1*);
myWeight.Push(myWeight1);
}*

thanks in advance._

If you haven’t already, check out the Unity script reference page on arrays.

Unity’s JavaScript allows you to use two types of arrays. This is oversimplified, but:

  • The Array class gives you a managed array with dynamic type and length
  • “Built-in” arrays are more traditional array with static type and length

So I realize this may not be intuitive, but you have a serious problem in your first set of examples…

This gives you one Array object:

var foo : Array;

This, on the other hand, gives you a built-in array of Array objects:

var foo2: Array[];

That second one won’t make sense in most cases, but it’s technically a valid type, so the compiler won’t necessarily complain about it.

The second problem you’re having is that declaring a variable doesn’t always give it a useful value. Declaring a variable merely reserves the name and type. You probably want to assign a value, too – in the case of “reference” variables, you’ll generally need to before using it.

This declares an Array:

//this will compile
//but you'll get a NullReferenceException if you access it before setting a value
var foo : Array;

This declares and creates an array:

//you can access this array immediately, because it's assigned upon declaration
var foo2 : Array = new Array();

//you don't always have to specify a type
//since you're providing a value, Unity can tell what type this var is
var foo3 = new Array();

So when you declare that variable, myMap, you’re sort of reserving a place where you can put an Array, but you haven’t actually put on there, just yet. So it’ll error out if you try to access it without putting anything there, first.

This can be a lot to wrap your head around, but practice does make perfect. It gets much easier, the more you do it.