Search code examples
actionscript-3instancemovieclip

How to get name of MovieClip on Flash stage that was created dynamically?


There are multiple MovieClips that will be dynamically placed on stage. These MovieClips are coded to be buttons. I'm trying to figure out--when a user clicks on the MovieClip...figure out which object on the flash stage the user clicked on.

Inside function toggleClick I put the trace statement:

trace("movieClip Instance Name = " + e.target.name);

In the OUTPUT window:

movieClip Instance Name = instance5 
movieClip Instance Name = instance12 
movieClip Instance Name = instance5 
movieClip Instance Name = instance32 
movieClip Instance Name = instance5 
movieClip Instance Name = instance59 

That doesn't seem the way to get a name for the MovieClip that was clicked.

Is getChildByName() the way to do it? If so, any ideas how to use getChildByName() to get the name of the MovieClip that was clicked?


Solution

  • Before adding a button to the stage you can actually name it

      var myButton:MovieClip = new MovieClip();
      myButton.name = 'button1';
    

    or

      var myButton:MovieClip = new MyButton(); //if you assigned a class name to your MovieClip
      myButton.name = 'button1';
    

    With your example you could do something like this:

      var comp:Comp = new Comp();
      var monitor:Monitor = new Monitor();
    
      addItemButton( comp, "comp" , {x:100, y:200});
      addItemButton( monitor, "monitor" , {x:30 , y:50} );
    
    
      private function addItemButton(item:MovieClip , itemName:String , params:Object):void
      {
         item.addEventListener(MouseEvent.CLICK , clickHandler );
         item.name = itemName;
    
         // of course params is not necessary, just making a point of  
         // how to centralize your concerns
         item.x = params.x;
         items.y = params.y;
    
         addChild( item);
      } 
    
      private function clickHandler(event:MouseEvent):void
      {
         trace( "button clicked:" + event.currentTarget.name );
      }