Nelson Sule
Nelson Sule

Reputation: 29

instantiate class objects from array values in AS3

Am trying to create new instances of classes in a loop where the class instance names have been defined in an array. how Do i turn the array values from string to objects? here's what i have written so far

var tiles2:Array = new Array("e1", "e2", "e3", ...);

for (var i = 0; i < tiles2.length; i++){
    if (i == 0){
        xPos = 18;
    }else if (xPos > 0 && xPos < maxGridWidth){
        xPos =+ xPos + objWidth + horGap;
        //trace(xPos);
    }else{
        xPos = 18;
        yPos =+ yPos + verGap + objHeight;
    }
    var this[tiles2[i]] = new tiles2[i];
    this[tiles2[i]].name = tiles2[i];
    this[tiles2[i]].x = xPos;
    this[tiles2[i]].y = yPos;
    tileArray[i] = this[tiles2[i]];
    addChild(this[tiles2[i]]);
}

This is where I have a problem var mc = new tiles2[i];. the desired output am looking is something like

var e1 = new e1;
e1.name = tiles2[i];
e1.x = xPos;
e1.y = yPos;
tileArray[i] = e1;
addChild(e1);

if you have a better procedure for doing this i will be glad if you can show me

Upvotes: 1

Views: 84

Answers (1)

Andrew Sellenrick
Andrew Sellenrick

Reputation: 1016

I believe you are looking for this...

// If tiles2[i] is a string that is the name of a class
var type:Class = getDefinitionByName(tiles2[i]) as Class;
var thing = new type();

// If tiles2[i] is a string instance name for an existing object:
var thing:DisplayObject = getChildByName(tiles[i]);

OR, perhaps you just need to change the line in question to this:

//var mc = new tiles2[i]; <-- line in question

//take out the var, and instantiate the proper class
this[tiles2[i]] = new e1();

Upvotes: 1

Related Questions