Search code examples
arraysactionscript-3functiontimeline

For each item (of a class) on the stage, add each item to an array?


trace(listOfCells)I don't understand how to do this. I currently have this code on the timeline:

var listOfCells:Array = new Array();

for (var i:int =0; i < stage.numChildren; i++)
{
    listOfCells.push(stage.getChildAt(i));
}

trace(listOfCells)

How would one type a code that adds each item of a class to the array? Because when I trace the array, it only says [object MainTimeline] once, not twice (I have two identical movieclips on the stage).

The reason for all this is so I can compare each movieclip's x and y value to every other one, and then move toward each other.

Thanks in advance.


Solution

  • You are doing right. To access the objects inside the array, again you need to loop through it . Try this,

    var listOfCells:Array = new Array();
    
    for (var i:int =0; i < this.numChildren; i++)
    {
        listOfCells.push(this.getChildAt(i));
    }
    
    var len:int = listOfCells.length;
    for (var j:int =0; j < len; j++)
    {
        trace(listOfCells[j].x);
    }
    

    or you can access the root of the application to get the elements like below,

    var listOfCells:Array = new Array();
    
    for (var i:int =0; i < (root as MovieClip).numChildren; i++)
    {
        listOfCells.push((root as MovieClip).getChildAt(i));
    }
    
    trace(listOfCells)
    
    var len:int = listOfCells.length;
    for (var j:int =0; j < len; j++)
    {
        trace(listOfCells[j].x);
    }