Search code examples
arraysactionscript-3loopsmovieclip

as3: how to access a MovieClip as unique Object/MovieClip from Array which loaded from same MovieClip from the Library


I'm trying to add multiple copies of the same movieclip to the stage at once

I have the loop which fills the array and generate the movieclips to the stage

and the loop to add The click EventListener for each movieClip

but I miss the magical code to access every MovieClip separately to have it removed from the stage by clicking on it

var numOfClips:Number = 5;
var mcArray:Array = new Array();

for(var i=0; i<numOfClips; i++)
{
    var usd:mcUSD = new mcUSD();

//genrate random x , y position----------------------------
    var randY:Number = Math.floor(Math.random()*460) + 120;
    var randX:Number = Math.floor(Math.random()*350) + 60; 
    usd.x = randX;
    usd.y = randY;  
//---------------------------------------------------------
    mcArray.push(usd);
    addChild(usd);
}

for(var m:int = 0; m<mcArray.length; m++){
    usd.addEventListener(MouseEvent.CLICK, colectmoney);
}

function colectmoney(e:MouseEvent): void { 
     removeChild(usd);
}

Solution

  • Try this:

    import flash.events.MouseEvent;
    
    var numOfClips:Number = 5;
    var mcArray:Array = new Array();
    
    for(var i=0; i<numOfClips; i++)
    {
    var usd:mcUSD = new mcUSD();
    
    //genrate random x , y position----------------------------
    var randY:Number = Math.floor(Math.random()*460) + 120;
    var randX:Number = Math.floor(Math.random()*350) + 60; 
    usd.x = randX;
    usd.y = randY;  
    //---------------------------------------------------------
    mcArray.push(usd);
    addChild(usd);
    }
    
    addEventListener(MouseEvent.CLICK, mouseClickHandler);
    
    function mouseClickHandler(e:MouseEvent) : void {
    removeChild(mcArray[mcArray.indexOf(e.target)]);
    }
    

    Important things to note: 1) you do not need to call a mouse.click event listener for each mcUSD object. It's more efficient to call it once. 2) removeChild(usd) won't work because you need to tell AS3 which mcUSD object to remove. 3) try to keep function nomenclature consistent - eg colectMoney instead of colectmoney. it will save you confusing times once your program gets bigger. hope this helps! :)