Search code examples
flashactionscript-3overridingrootaddchild

Overriding addChild() at root?


I've seen methods for overriding addChild inside of movieclips, but can you do it at the upper-most root level? As in, overriding it on the main timeline.


Solution

  • Here's what you need to do. First create a document class for your FLA. In this case, I've called it Main.as:

    package
    {
        import flash.display.DisplayObject;
        import flash.display.MovieClip;
    
        public class Main extends MovieClip
        {
            public function Main()
            {
                var spr : MovieClip = new MovieClip();
                spr.graphics.beginFill(0x666666, 1);
                spr.graphics.drawRect(0, 0, 100, 100);
                addChild(spr);
            }
    
            override public function addChild (child : DisplayObject) : DisplayObject
            {
                // Do whatever it is you need to do here, but remember to call super.addChild() if you actually want to get anything added to the stage.
                trace ("I'm gonna add the heck out of this child: " + child);
                return (super.addChild(child));
            }
        }
    }
    

    Then you need to set the document class in your FLA (look at the Property panel with no stage objects selected).