Search code examples
actionscript-3flashremovechildanimate-cc

ActionScript 3: Adding multiple instances of the same object to the stage and removing each separately


I have a piece of code adding three insances of the same MovieClip to the stage. I also added MouseEvent.CLICK listener. Once any of the MovieClips gets clicked, I want it to be removed from the stage. My problem is, whenever any of the elements gets clicked, only the last one gets removed and when I click again on a different instance, I'm getting:

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

I added these three MovieClips to an array, but I don't know how I can properly identify which instance got clicked and remove only the said instance.

This is the excerpt of code I have:

var myMC: SomeMC;
var myArray: Array = [];


function Loaded(e: Event): void {
	
	for (var i: int = 0; i < 3; i++) {
		
	myMC = new SomeMC();

	myMC.addEventListener(MouseEvent.CLICK, Clicked);
	
	myMC.y = 50;
	myMC.x = 50 * i;
	
	addChild(myMC);
	
	myArray.push(myMC);

	}		
}

function  imageClicked(e: MouseEvent){
	
  // Only the last instance gets removed.
  
	e.currentTarget.parent.removeChild(myMC);
  
  }

I'd be grateful for any help.


Solution

  • In Loaded function you create 3 instances of the object, but by doing:

    myMC = new SomeMC();

    you overwrite reference. In first iteration myMC is 1st one, in 2nd 2nd one, etc...

    Then in imageClicked you're trying to remove it. 1st time it's working because it's referencing the last object, but after you removed it from stage it won't work anymore.

    How about changing e.currentTarget.parent.removeChild(myMC); to e.currentTarget.parent.removeChild(e.currentTarget); ? That should remove clicked one.