Skip to main content
Participant
June 9, 2011
Answered

Dynamically add instance of a class

  • June 9, 2011
  • 2 replies
  • 540 views

Im trying to dynamically add instances of a class. I need to do it in a loop. How would I go about doing something of that nature?

This topic has been closed for replies.
Correct answer Ned Murphy

Basically...

for(var i:uint=0; i<numInstancesNeeded; i++){

    var newInstance:YourClassName = new YourClassName();

    addChild(newInstance);

}

2 replies

Participating Frequently
June 9, 2011

Or do you mean something like this ?

for (var i:int = 0; i < 10; i++)

{   
     var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class;

     var mySprite:Sprite = new ClassReference() as Sprite;

}

Ned Murphy
Ned MurphyCorrect answer
Legend
June 9, 2011

Basically...

for(var i:uint=0; i<numInstancesNeeded; i++){

    var newInstance:YourClassName = new YourClassName();

    addChild(newInstance);

}

Participant
June 9, 2011

okay i was thinking that it would be refering to the same instance since your id be using the same instance name.  Thank you.

Ned Murphy
Legend
June 10, 2011

If you need to target specific instances afterwards, then you can store the instances in an array (usually easiest) as you add them, or you can assign them names that involve the loop increment (which can require the use of getChildByName to target them).