2 Replies Latest reply on May 8, 2007 10:08 AM by Newsgroup_User

    AS3: addChild()

    Rothrock Level 5
      I'm just getting into AS3 and it is making me crazy. All over the place (help files etc.) I see code like this.

      addChild(myLoader);

      Where myLoader is an instance of the Loader class. But it could be a Sprite or something else. But to what are we adding the child? It seems that Loader inherits like this (has anybody else noticed that copying from the help files never seems to work on the first try?):

      Loader DisplayObjectContainer InteractiveObject DisplayObject EventDispatcher Object

      And it seems that addChild() is inherited from the DisplayObjectContainer class. So is the addChild adding the loader to itself?
        • 1. Re: AS3: addChild()
          abeall Level 3
          addChild is basically the replacement for attachMovie, createEmptyMovieClip, and duplicateMovieClip. You use it to add DisplayObjects to a DisplayObjectContainer.

          Loader is basically a type of DisplayObjectContainer, anything you load is automatically added to it as a child, and you then add the Loader itself to a visible DispalyObject to actually see it. You can access the loaded child content via Loader.content.

          Not sure if that answers your question or not :-)
          • 2. Re: addChild()
            Level 7
            When you create a DisplayObject using the new operator, it has no parent.
            The addChild method allows you to change the objects parentage -- a real
            improvement for Flash.


            Try this snippet in the timeline:


            import flash.display.*;
            import flash.events.MouseEvent;

            var s1:Sprite = new Sprite();
            var s2:Sprite = new Sprite();

            s1.x = 10;
            s1.y = 10;

            s2.x = 200;
            s2.y = 10;
            this.addChild(s1);
            this.addChild(s2);

            var rect:Shape = new Shape();
            rect.graphics.beginFill(0xff0000);
            rect.graphics.drawRect(0,0,100,100);
            rect.graphics.endFill();
            rect.x = 20;
            rect.y = 20;
            s2.addChild(rect);
            s2.addEventListener(MouseEvent.CLICK, clickHandler);
            s1.addEventListener(MouseEvent.CLICK, clickHandler);

            function clickHandler(event:MouseEvent){
            if(event.target == s1){s2.addChild(rect);}
            else{s1.addChild(rect);}
            trace(rect.parent.name)
            }