PDA

View Full Version : Arrays of Custom Objects


WhoCares357
12-31-2008, 09:57 PM
I can't seem to figure out how to create an array of objects in AS3. For example, if I wanted to create an array of the textField object how would I go about doing it?

rondog
12-31-2008, 10:09 PM
Not sure I understand the question, but...

var text1:TextField = new TextField();
var text2:TextField = new TextField();
var text3:TextField = new TextField();

var arr:Array = [text1,text2,text3];

for (var i:int = 0; i < arr.length; i++)
{
trace(arr[i]);
}

WhoCares357
12-31-2008, 10:50 PM
Not exactly. I want to create a dynamic array of something (like a bullet in a game). When the player clicks the mouse it'll add an element to the existing array of the bullet object. I can then control each individual bullet dynamically (by cycling through them).

I've done this in pascal like this:

//create a new type named bullet

var
myBullet: Array [0..10] of bullet;

begin
for i := 0 to myBullet.length do
myBullet[i].onStage := true; //sets the onStage property for each instance of myBullet
end.

devilmaycry
12-31-2008, 11:15 PM
see about Vector Class
http://help.adobe.com/en_US/AS3LCR/Flash_10.0/index.html

Mazoonist
01-01-2009, 12:01 AM
In actionscript you don't designate the type when you make an array, there are no typed arrays. An array's elements can hold any data type, so even a mixture of types can be stored in the same array.

Also, you don't need to specify up front how many elements the array will hold. Just instantiate your array and then later push items into it:
var bulletArray:Array = new Array();
// then later in the program:
bulletArray.push(new Bullet()); //of course, make sure you have a Bullet class
You might want to create the array as a static member of a class, that way there's only one copy. You might even do this in the Bullet class:
public static var bulletArray:Array = new Array();
//then, elsewhere in the program (even from another class):
Bullet.bulletArray.push(new Bullet());

Anytime you want to, you can use a for loop to cycle through this static array and do whatever you want with the bullets, from anywhere in your program:
for(var i:int = 0; i < Bullet.bulletArray.length; i++) {
Bullet.bulletArray[i].doSomething(); //whatever you want to do (?)
}

WhoCares357
01-01-2009, 02:23 AM
Thanks for both replies. I'll use the information well.