Search code examples
actionscript-3actionscriptflashdevelop

How to remove all MovieClips, Sprites and graphics from a scene in AS3?


I have a scene including all MovieClips, Sprites, graphics that I bring some of them to the stage using addChild(...).

I want to remove all of them because I can still see them when I go to other scenes.

I have used below code but it shows me the error mentioned below:

btn.addEventListener(MouseEvent.CLICK,removing);

function removing(e:MouseEvent):void
{
  while (stage.numChildren > 0)
  {
    stage.removeChildAt(0);
  }

}

Error:

TypeError: Error #1009: Cannot access a property or method of a null object reference. at Show_fla::MainTimeline/removing()

Thanks in advance for your time and help!


Solution

  • As it shows, it is not working with while loop and it is working with for loop|:

    btn.addEventListener(MouseEvent.CLICK,removing);
    
    function removing(e:MouseEvent):void
    {
     var i:int = 0;
     for (i=stage.numChildren-1; i>=0; i--)
     {
        stage.removeChildAt(i);
     }
    }