classactionscript-3objectmovieclipdisplaylist

Adding objects to the DisplayList using variable


Im trying to add objects to the displaylist, but for my project it would be good if i could run one piece of code that could place 1 of 5 objects onto the screen. Currently the code works if I put in the name of the object, but fails if I try to give it the class name through a variable. Any Ideas?

var sides:Array = new Array(Edge, Edge, Edge, Edge, Edge, Edge); 

var side1:sides[0] = new sides[0]();
centerHex.addChild(side1);
side1.y = side1.y - 20;

Throws this error:

1086: Syntax error: expecting semicolon before leftbracket.

This code works though:

var side1:Edge = new Edge();
centerHex.addChild(side1);
side1.y = side1.y - 20;

Any Ideas? Any help is appreciated.


Solution

  • You cannot declare variable as something from Array, because variable declaration is a compile-time operation, while Array items are available at runtime, which is later.

    Also, you don't need to. Just declare it as DisplayObject, or don't declare at all, it is not mandatory, you are not obliged to, and it will be fine:

    var Sides:Array = [Edge, Edge, Edge, Edge, Edge, Edge]; 
    
    for (var i:int = 0; i < Sides.length; i++)
    {
        var SideClass:Class = Sides[i];
        var aSide:DisplayObject = new SideClass;
    
        var anAngle:Number = i * Math.PI / 3;
    
        aSide.x = 100 * Math.cos(anAngle);
        aSide.y = 100 * Math.sin(anAngle);
        aSide.rotation = anAngle * 180 / Math.PI;
    
        centerHex.addChild(aSide);
    }