Game Development Reference
In-Depth Information
Listing 1.24 Storing Game Objects in an Array
function Start ()
{
var aP:Array = new Array(9);
for(var i:int = 0 ; i < 9 ; i++)
{
aP[i] = GameObject.
CreatePrimitive(PrimitiveType.Cube);
aP[i] .transform.position.y = i + 1;
}
}
The first box in the array is indexed with a 0. To refer to each box individually,
their names are aP[0] , aP[1] , aP[2] , aP[3] , aP[4] , aP[5] , aP[6] , aP[7] , and aP[8] .
This is the reason for changing the for loop in Listing 1.24 to begin counting
at 0. The variable i can be used as the array index. The first time the loop runs,
aP[i] is equivalent to writing aP[0] .
Because the y position of the first cube was initially 1 and i now starts at 0, the
position must be set with i + 1 to keep this consistent.
Unity Hands On
Arrays
and open in Unity. In the Project, double-click on coloredCubes
to open the scene. The Scene will appear empty. Attached to the
Main Camera is the script called stackedColors.js . Play the file. A
vertical stack of colored cubes will appear in the Game as shown in
Figure 1.31 .
Step 2. Open stackedColors.js in the script editor. Note that in the
Update() function only four of the cubes are assigned a color. Also, the
array declaration has been moved to the top of the script. This is to
make aP a global variable available to all functions, not just Start() .
Step 3. Modify stackedColors.js to the code shown in Listing 1.25 .
Listing 1.25 Setting an Array of Cubes to the Color Red
private var aP:Array = new Array(9);
function Start ()
{
for(var i:int = 0; i < 9; i++)
{