1

I'm having a problem with my AS3 flash script.

I have an array of 3 movieclip items, I want to play each one with a timer delay of 1 second between each item. However when placing a timer class around the 'play' instantiation it returns an error of an undefined property.

//Randomise MC array
function randomSort(a:*, b:*):Number
{
    if (Math.random() < 0.5) return -1;
    else return 1;
}
var obstacleArray:Array = [obstacleCar,obstacleCar2,obstacleCar3];
obstacleArray.sort(randomSort);


trace(obstacleArray);
trace(obstacleArray.length);

//Delay initially 1 second upon entering frame
var timerPlay:Timer = new Timer(1000,1);
timerPlay.addEventListener(TimerEvent.TIMER, ontimerPlay);
timerPlay.start();
function ontimerPlay(evt:TimerEvent):void{

    //FOR EACH OBSTACLE, Run through array delaying each item by 1 second

    for(var i:Number=0; i<obstacleArray.length; i++){

        var timerDelay:Timer = new Timer(1000,1);
        timerDelay.addEventListener(TimerEvent.TIMER, ontimerDelay);
        timerDelay.start();
        function ontimerDelay(evt:TimerEvent):void{

        obstacleArray[i].play();
        trace(obstacleArray[i]);

        trace(i);
            }
        }
}

Thank you so much if you can help me!

user2075625
  • 93
  • 2
  • 11
  • You cannot use "i" variable within a nested function. – Vesper Feb 15 '13 at 13:49
  • @Vesper I didn't see any error/warnings about i's usage in the nested function when I copy pasted in Flash CS5 – abnvp Feb 15 '13 at 14:13
  • It's been suggested that I should use a return function? The problem only occurs the moment I begin to use the timerDelay timer class inside the for loop – user2075625 Feb 15 '13 at 14:32

2 Answers2

0

If you see the trace(i)'s output, the output should be 3 always. This is happening because the when the eventHandler is called, the value of i has already been incremented to 3. At index 3, you don't have any obstacle.

abnvp
  • 1,037
  • 11
  • 19
0

Welcome to the world of closures!

Apparently in ActionScript you have to do some hackery to get this to work right; this question asks about pretty much the same situation you're in -- the answer worked for me:

How do you bind a variable to a function in as3

Community
  • 1
  • 1
paul
  • 1,655
  • 11
  • 23