2

I have problem that I need to create timer but I want to pass on a variable to it, how to do it? Is it possible in AS3?

I tried like this:

            bonusPlayer1Timer = new Timer(5000);
            bonusPlayer1Timer.addEventListener(TimerEvent.TIMER, bonusChanges(player1));
            bonusPlayer1Timer.addEventListener(TimerEvent.TIMER_COMPLETE, bonusChangesRemove(player1));
            bonusPlayer1Timer.start();

function bonusChanges(event:TimerEvent, playerBonus:Player):void {
    switch (playerBonus.bonus) {
        case 0 :
            playerBonus.multipleShooting = false;
            playerBonus.bonus = -1;
            break;
...}}

But I have error:

1067: Implicit coercion of a value of type Player to an unrelated type flash.events:TimerEvent.
1136: Incorrect number of arguments.  Expected 2.

And this error is in the bold line.

Can I use it in this way? Or I have to create two the same function for every of my players because I am not allow to pass on any different arguments to the timer function?

Thank you,

canimbenim
  • 659
  • 4
  • 10
  • 23

4 Answers4

8

Create a class that extends the Timer class and add a property for the Player.

public class PlayerTimer extends Timer
{
    public var thePlayer:Player;

    public function PlayerTimer(delay:Number, repeatCount:int=0)
    {
        super(delay, repeatCount);
    }       
}

Using your example the code would be something like this:

bonusPlayer1Timer = new PlayerTimer(5000);
bonusPlayer1Timer.thePlayer = new Player();
bonusPlayer1Timer.addEventListener(TimerEvent.TIMER, bonusChanges);
bonusPlayer1Timer.addEventListener(TimerEvent.TIMER_COMPLETE, bonusChangesRemove);
bonusPlayer1Timer.start();

function bonusChanges(event:TimerEvent):void {
    var playerBonus:Player = PlayerTimer(event.target).thePlayer; 
    switch (playerBonus.bonus) {
        case 0 :
            playerBonus.multipleShooting = false;
            playerBonus.bonus = -1;
            break;
...}}
Nathan Smith
  • 36,807
  • 6
  • 28
  • 25
  • Very nice mate just unlocked some knowledge for me there. Extend the class your interested in and allow it to attach a custom class. So event.target references the Timer object that has just triggered an event, right? – Alex Apr 18 '11 at 04:24
2

You can never pass more than one argument into the function triggered by an EventListener. You need to find other ways of passing your information around, such as the solution provided by Nathan Smith.

Mark D
  • 1,309
  • 4
  • 19
  • 38
0

you can also do it this way:

var x = setTimeout(yourfunction(/*arguments you need*/),1000);
function yourfunction(/*var*/){
    //your code
}
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Nicolas Sleiman
  • 124
  • 1
  • 8
0

Just Type var bonusPlayer1Timer = new Timer(5000);