- Home /
Syntax to initialize 2D (Jagged), built-in array at runtime
I want to create a "jagged" built-in array of GameObjects in Unity Script. The first dimension will always have 4 elements, but I want to define the length of each sub-array at runtime. I've tried:
private var armorBarReferences : GameObject[,];
armorBarReferences = new GameObject[4];
Which returns: Cannot convert 'UnityEngine.GameObject[]' to 'UnityEngine.GameObject[,]'.
I also tried:
private var armorBarReferences : System.Array[];
armorBarReferences = new System.Array[4];
But with the second case, something like:
armorBarReferences[currentArc][i] = Instantiate(armorBarObject, position, rotation);
armorBarReferences[currentArc][i].transform.localScale += Vector3(1, 1, 1.1);
Gives: 'transform' is not a member of 'Object'.
I think I could do this with a JavaScript Array class as the first dimension, but wanted to learn the "right" way. The size of the arrays will never change once I've set them, so the built-in arrays seemed the right choice.
Answer by Azzara. · Apr 14, 2013 at 10:04 AM
GameObject[,] is a not a jagged array. It is called a multi-dimensional array. GameObject[][] is a jagged array. Which one do you want to use? If all 4 elements have the same length n, then yes, your multi-dimensional array GameObject[,] is the right choice.
However, you can't change the size of the second dimension of a GameObject[,] at runtime. You have to set both sizes when you initialize the array. Like this
var n = 100; // decide what element length to use at runtime
armorBarReferences = new GameObject[4, n];
Edit: If you need a jagged array GameObject[][], it is a little tricky to declare it in Javascript. You can try this
private var dummy : GameObject[] = null;
private var armorBarReference = [ dummy, dummy, dummy, dummy ];
Ah, I want to use a Jagged array, since all four elements will have different lengths. This looks right, but private var armorBarReferences : GameObject[][];
gives me the error: ';' expected. Insert a semicolon at the end.
Is Unity not able to define built-in arrays in this manner still?
Not with Unityscript, only C#. With Unityscript you can only declare them implicitly, such as var foo = [[1, 2], [3, 4, 5], [6]];
So is there no way to initialize my jagged array after the declaration?
It would probably be easier just to use a List of GameObject arrays. There are no issues doing that in Unityscript and it has the same effect as a jagged array.
In C# you could write
private GameObject[][] armorBarReference = new GameObject[4][];
I've managed to achieve the same in Javascript.
private var dummy : GameObject[] = null;
private var armorBarReference = [ dummy, dummy, dummy, dummy ];
In both cases you get a new GameObject[4][]. The first dimension is set to 4. The second dimension is not set yet. To set the dimension of the fourth element to 100 try
armorBarReference[3] = new GameObject[100];