Search code examples
actionscript-3

Adding multiple instances of the same object


Adding multiple instances of the same object The movie clip disappears from the first object because the instance name is Always the same is there a solution

var mc1:Mc1=new Mc1();
var mc2:Mc2=new Mc2();


var ar:Array=new Array();

function fun(){
var i = 0;
while (i < ar.length) {
ar[i].width=864;
ar[i].height=651;
ar[i].x=200;
ar[i].y=200;	
ar[i].visible=false;		
addChild(ar[i]);
i++;	
}
TweenMax.staggerTo(ar,0, {visible:true},0.120);
}

button1.addEventListener(MouseEvent.CLICK,f1);
function f1(e:Event):void{
ar.push(mc1);//
}
button2.addEventListener(MouseEvent.CLICK,f2);
function f2(e:Event):void{
ar.push(mc2);
}
button3.addEventListener(MouseEvent.CLICK,f3);
function f3(e:Event):void{
ar.push(mc1);//
}
button4.addEventListener(MouseEvent.CLICK,f4);
function f4(e:Event):void{
fun();
}


Solution

  • you are only ever creating two instances, one of Mc1 and one of Mc2 at the very top of your code. If you don't see the word new, your not creating any new instances.

    What you likely are wanting to do, is store the Class in the array, then in the while loop create a new instance of that class.

    1. Change the places where you push to the array, to push the class name, not the instances:

      ar.push(Mc1);  //instead of ar.push(mc1)
      
    2. Remove those instances at the top

      //remove these two lines
      var mc1:Mc1=new Mc1();
      var mc2:Mc2=new Mc2();
      
    3. Change your while loop to create a new instance of the class in the array

      var obj:MovieClip; //create a var to store your Mc objects in the loop below
      var i:int = 0;
      while (i < ar.length) {
          obj = new ar[i](); //this instantiates the class stored in the array at index i
          obj.width=864;
          obj.height=651;
          obj.x=200;
          obj.y=200;  
          obj.visible=false;      
          addChild(obj);
          i++;    
      }