Flash / Actionscript: Create an Array of Objects from a Unique Class

Contributor Icon Contributed by davak Date Icon May 13, 2006  
Tag Icon Tagged: Computer programming

When starting in AS2, I found it difficult to make an array of objects after creating my own class. Hopefully, this little tutorial will make it easier for others.


I spent 8 hours trying to figure this out initially. To me actionscript handles this a little differently than other programming languages.

Basically we will create a small class, create an object with that class, and then load that object into an array.

First we create our class. Remember to create a class, you have to do it from a seperate actionscript file.

//in testclass.as
class testClass
{
//Establishes the first variable in your testClass
public var first: String;
}

Now, here is the heavily commented code that should be in your main actionscript file.


//Import your unique class--testClass
import testClass;

//create tC object from your test class

//create an array to hold the objects
var theArray:Array = new Array();

//create loop with i as the counter
for (var i=0; i<4; i++)
{
//create tC object from your test class
var tC:testClass = new testClass();

//assign text to the first variable.
//i included to prove that we are assigning different data
//to each object in the array
tC.first = "asdf" + i; //asdf0, asdf1, etc.

//push the object into the array
theArray.push(tC);
}

//Another loop with ii as counter
for (var ii=0; ii<4; ii++)
{
//shows that the array contains an array of objects
//and demostrates how to extract the values from them

trace (theArray[ii].first);
//asdf0,asdf1, etc.

}

Easy, huh?

Previous recipe | Next recipe |
 
  • Fantastic!

    Thx!!!!
  • tim
    I tried a few different ways I thought made sense, too, but nothing worked. I didn't think I'd find much specifics on inserting objects into an array, but this helped a LOT. THANKS!
  • Thanks a lot, this was really useful. The same method transfers to AS3 by the way if anyone was wondering
  • SelfLearner
    Perfect,
    it saved my day...

    thanks
  • This is very useful for game programming
  • You don't really need to create a new class to hold your object. You can simply define your object inline with a variable declaration.
    ex:
    protected var testClass:Object = {first:null};

    The rest of the code remains the same and this works the same as putting the object in a class of its own.

    EDIT: Apparently this method overwrites stuff inside the array, so the object definition should be inside the for loop.
blog comments powered by Disqus