Gabriel Meono
Gabriel Meono

Reputation: 1010

If statement in AS3 not working

This is an if stament on a frame on the root. I want to loop Carrera(a lenghthy movieclip) from frame 2 back to frame 1. (For testing purposes)

This is the code:

if (MovieClip(root).Carrera.currentFrame==2){
   MovieClip(root).Carrera.gotoAndPlay(1);
}

The MovieClip keeps going, ignoring the if statement. What I'm doing working?

Upvotes: 1

Views: 1155

Answers (3)

Cameron
Cameron

Reputation: 98886

There's no bug with the if statement, it's just not being evaluated when you expect it to be.

When you place code in a frame, it gets executed right away, when that frame gets entered. So, when the first frame starts, the if is executed, whose condition is false at that time. And it never gets re-executed, because you never tell it to be. There is no such thing as "standing orders" in AS3 ;-)

Instead, you can check on every frame by adding an event listener:

addEventListener(Event.ENTER_FRAME, function (e) {
    if (MovieClip(root).Carrera.currentFrame==2){
        MovieClip(root).Carrera.gotoAndPlay(1);
    }
});

Or, you can just place gotoAndPlay(1); on the second frame of Carrera (not the root).

Upvotes: 2

weltraumpirat
weltraumpirat

Reputation: 22604

You have to understand that you are running this if statement only once. Even if the Carrera clip is at frame 2 in that exact moment, the clip will jump to play 1 and continue playing - there is nothing to make it do the jump again, and thus there can never be a loop.

In order for this to work, you have to run this same statement again and again - every time the clip jumps to a new frame.

For example, you can do this by a) attaching this script to frame 2 of the Carrera clip (not the root!):

gotoAndPlay(1);

or b) adding an event listener to it:

MovieClip(root).Carrera.addEventListener (Event.ENTER_FRAME, 
    function ( ev:Event ) : void {
        var cl:MovieClip = ev.target as MovieClip;
        if (cl.currentFrame == 2) cl.gotoAndPlay(1);
    }

There are many more ways to do this, but unless you are going to do more complicated things than jumping to frames every now and then, I would advise you to go for the first option - it seems you should learn more about ActionScript before trying out event listeners.

Upvotes: 2

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28429

Things to test...

Is MoveClip(root) defined at the point in execution?

Is MoveClip(root).Carrera defined at the point in execution?

Is MovieClip(root).Carrera playing (or have you called stop on it so it's just sittin in frame 1?

Upvotes: 0

Related Questions