Beginner's Guide: Using Arrays
Learn the basics of constructing and using arrays to manage your game data.

So far in this tutorial, you’ve become familiar with using predefined classes, and, in the case of wanting to encapsulate data that you know you’ll use regularly, creating your own classes.

But there is another type of data organization you’ll want to know about and use. You will likely have to work with large numbers of similar objects — similar enough, in fact, that they are all the same type of class. They may be GameObjects, Texture2D objects, or other types of objects. You will have several of them, and will want to perform a similar operation on all of them.

For instance, if you had a group of GameObjects that you wanted to draw on the screen, and each had its own position and Texture2D, the code you would write for each GameObject would be exactly the same. Currently, though, you would have to write the same code for each GameObject, cluttering up your codebase. Is there a way to simply run a set of objects past the same code, and have the code interact on each of the objects the same way?

There is — the solution can be found in arrays. An array is a linear collection of objects of the same type. You can have an array of any type; an array of Vectors, an array of GameObjects, an array of strings, all of these arrays are possible and valid.

The diagram shows the sequence of code for creating a three-element array of GameObjects. You declare the array using [] after the type name, which indicates you want an array of the given type. You then initialize the array using new and [x], where x is the size of the array in elements.

If the type of object in the array is a class, you must also loop through the array and initialize each object within the array elements.

Once this is done, you can now access each element of the array using the name of the array followed by [x], where x is the element you want to access, starting with zero as the first element. Because the indices start at zero, calling cannonBalls[1].position would give you the position variable for the second GameObject in the array.

A more powerful way to access arrays is the for loop, which is demonstrated in the diagram above. A for loop allows you to run the same code against all elements in an array. You can also use a foreach loop, which will be demonstrated in the following step. Both methods allow you to run the same code for multiple elements of the same type. This allows you to reuse code you’ve already written and not have to code more, even if the size of the array grows later on.

var gDomain='m.webtrends.com'; var gDcsId='dcschd84w10000w4lw9hcqmsz_8n3x'; var gTrackEvents=1; var gFpc='WT_FPC'; /*<\/scr"+"ipt>");} /*]]>*/
DCSIMG