开发者

AS3: Problem addressing movie clips in an array!

I'm using loops to create a grid of movie clips. The clips are stored in an array tileArray.

H开发者_运维问答ere is my code:

//Spawn Checkers
var i:int = new int();
var j:int = new int();
var tileArray:Array = new Array();
for (i=0; i<22; i++)
{
    for (j=0; j<12; j++)
    {
        var tile:checker = new checker(i * 25 + 49,j * 25 + 40);
        stage.addChild(tile);
        tileArray.push(tile);
    }
}
//Activate Checkers (TEST)
var m:int = new int();
for (m=0; m<tileArray.length; m++)
{
    tileArray[m].gotoAndPlay(1);
}

My problem is when the //Activate Checkers (TEST) code section is run it doesn't address the 0th element. Namely the first tile created at position (49,40). If I do tileArray[0].gotoAndPlay(1); it works, but for some reason the for loop will hit every tile but the first checker object in tileArray.

e: When using trace(m); I can see that m does indeed start at 0, but the loop fails to execute tileArray[0].gotoAndPlay(1). Additionally, if I put tileArray[0].gotoAndPlay(1); outside of the loop and comment out the loop none of the tiles animate. tileArray[0].gotoAndPlay(1); doesn't work outside the loop, but does work inside - except when the array index is my iterative variable. Very strange.


You could simplify your code a bit, and it may fix the problem:

//avoid the use of the **new** statement (it initialise a bunch of stuff you dont need)
var i:int; 
var j:int;
var tileArray:Array = [];

for (i=0; i<22; i++)
{
    for (j=0; j<12; j++)
    {
        //** updated ** I forgot to add the [i] for index position
        tileArray[i] = new checker(i * 25 + 49,j * 25 + 40);
        addChild(tileArray[i]);
    }
}

//Activate Checkers (TEST)
var m:int;

for (m=0; m<tileArray.length; m++)
{
    tileArray[m].gotoAndPlay(1);
}


When I need to loop through an entire array, I generally use the for/each syntax:

for each (var tile:checker in tileArray) {
  tile.gotoAndPlay(1);
}

That doesn't explain the weird behavior you are encountering (I have no clue, I would start looking at the "checker" class but that's flailing) but it may make it irrelevant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜