Dynamically+adding+MovieClips

code format="actionscript3" var tempBox:Box; tempBox = new Box; addChild(tempBox); code
 * Suppose you have a MovieClip symbol in your library that is called "Box." How can you make an instance of Box show up on the stage, using only Actionscript? (In other words, without making the Box instance appear in the original .fla file?) (Pick "Widget"...."Insert Code"..."Actionscript 3" from the editing bar)**


 * If the Box symbol is linked to a "Box.as" file, what happens when you first say new Box?**

It runs the Box's constructor function. (The one that has the same name as the class.)

code format="actionscript3" var i:int; for (i=0; i<5; i++) {   var tempBox:Box; tempBox = new Box; addChild(tempBox); } code
 * How might you use a loop to create 5 Box instances on the screen, all at the same location?**

Before the loop, create the array. In your list of variables, say code format="actionscript3" var boxArray:Array; code and in your constructor (before the code loop from the previous question), create the array: code format="actionscript3" boxArray = new Array; code Then, in the code loop from the previous question, inside the loop itself but after you have created the new Box;, add the line: code format="actionscript3" boxArray.push(tempBox); code Each box gets put at the front of the screen, so whichever box you added as a child last will be the one on top.
 * How might you modify the loop above so that you also put the 5 Box instances in an Array?**
 * Which of these Box instances will be the frontmost one that the user can see?**

Here is a more complete piece of code, presumably all in the constructor, with the boxArray already declared to be an Array: code format="actionscript3" var i:int; boxArray = new Array; for (i=0; i<5; i++) {   var tempBox = new Box; tempBox.x = 10+i*20; // first box is 10 from left edge, and each box is 20 pixels over from the previous one. tempBox.y = 40; addChild(tempBox); boxArray.push(tempBox); } code
 * How might you use a loop to create 5 Box instances, arranged in a row, so they don't all overlap? (Suppose the box is naturally 20 x 20 pixels)**
 * Advanced (and thus optional) Note: it is also possible to add objects (such as the Box) to other MovieClips, so that they are sub-clips. Instead of just saying addChild(tempBox), you can say //objectInstanceName//.addChild(tempBox). However, note that this means that when the parent clip moves, the sub clips will automatically move with it - the x, y coordinates of the subclip refer to the //relative// position of the subclip within the parent clip.**
 * (Even more advanced note: In fact, when you just say addChild(tempBox) you are still doing this; it's just that the movieClip whose .as file you are in becomes the parent.) - HH**