Monday, December 23, 2024
HomeComputer programmingFlash/ActionScript: Create an Array of Objects from a Unique Class

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

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 eight hours trying to figure this out initially. To me, actionscript handles this a little differently from other programming languages.

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

First, we create our class. Remember, to create a class, you have to do it from a separate 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. }

This rather simple tutorial should prove helpful.

David Kirk
David Kirk
David Kirk is one of the original founders of tech-recipes and is currently serving as editor-in-chief. Not only has he been crafting tutorials for over ten years, but in his other life he also enjoys taking care of critically ill patients as an ICU physician.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!