Search code examples
actionscript-3clipaddchild

Clip inside clip created by AS3


There are two clips:main_mc and child_mc. The main_mc is on main-timeline of stage. The child_mc is inside main_mc, and is created by AS3 code:

var child_mc:Sprite=new Sprite;
child_mc.graphics.beginFill(0xff0000);
child_mc.graphics.drawCircle(15,20,10);
addChild(child_mc);

How to change, for example x,y , in child_mc, by AS3 created on main-timeline?


Solution

  • When you create a var inside a timeline, it becomes a property of that MovieClip, so you can access it like any other property

    So, on the main timeline, you can do the following:

    main_mc.child_mc.x = 100; 
    main_mc.child_mc.y = 100;
    

    If I'm misunderstanding, and you want the other direction, you use the root or parent keywords:

    So, from within main_mc, you can access the main timeline like so:

    MovieClip(parent)
    

    So if you had another object on the main timeline called myClip, and you wanted to hide it with code inside of main_mc, you could do:

    MovieClip(parent).myClip.visible = false;
    

    Or, from anywhere:

    MovieClip(root).myClip.visible = false;
    

    EDIT

    It would seem from your comment, that you are attempting to access child_mc on the same frame of the main timeline where main_mc is created. The problem with this, is that the main timeline code will run before the timeline code of any of it's children. (so child_mc isn't created yet when you main timeline code runs).

    If you need a way to wait until all children timeline code has run, you can do this as a workaround:

    //add a listener to wait until the frame is done being constructed.
    this.addEventListener(Event.FRAME_CONSTRUCTED,frameConstructed);
    
    function frameConstructed(e:Event):void {
        //remove the listener so this function doesn't keep running on subsequent frames
        this.removeEventListener(Event.FRAME_CONSTRUCTED, frameConstructed);
    
        //do what you need to here
        trace(main_mc.child_mc);
    }