Skip to main content
Inspiring
November 7, 2016
Answered

Restarting and variable scope

  • November 7, 2016
  • 1 reply
  • 553 views

Hello,

   I am using canvas and am setting some variables in the first frame of an animation. I want to be able to replay the animation and restart all of the children, but it seems that the vars I am setting are getting reset back to their original state when I rewind. Is there a clean way to not have the variables I am initializing change on restart?

function restart() {

   

    //console.log(doReplay);

    if (stage && stage.children) {

        var i, l = stage.children.length;

        for (i = 0; i < l; i++) {

            var child = stage.children;

            if ("gotoAndPlay" in child)

                stage.gotoAndPlay(0);

        }

    }

   

}

    This topic has been closed for replies.
    Correct answer Colin Holgate

    The variable ought to have automatically become a window variable, but it does seem to fail. Try setting it as a window variable:

    if (!window.iHaveBeenInitialized) {

         window.iHaveBeenInitialized = true;

         alert("hi");

    }

    1 reply

    Legend
    November 7, 2016

    Then start your animation on the second frame instead of the first. Sometimes the simplest solution is the best.


    If you simply must return to the same frame as your initialization code, when wrap it in a conditional like this:

    if (!iHaveBeenInitialized) {

         iHaveBeenInitialized = true;

         initialization code...

    }

    aewuAuthor
    Inspiring
    November 8, 2016

    Yes, I tried this, but it doesn't work because if you set iHaveBeenInitialized to false initially (you have to set it to something otherwise you get an undefined error) and then you rewind, it resets to false again.

    There has to be a way to initialize global variables that don't reset on replay?

    Colin Holgate
    Colin HolgateCorrect answer
    Inspiring
    November 8, 2016

    The variable ought to have automatically become a window variable, but it does seem to fail. Try setting it as a window variable:

    if (!window.iHaveBeenInitialized) {

         window.iHaveBeenInitialized = true;

         alert("hi");

    }