PDA

View Full Version : beginner: add instances programatically


max1x106
02-21-2007, 11:26 PM
I see how to add instances of a symbol to the stage and give them instance names with the property inspector during design time.

But, I would like to add instances of a movie clip, Ball_mc, to the stage at run time giving the instances a loopable name.

I just don't know how. Is there a load event for a layer I can attach a loop to? What is the syntax to name (in an indexed fashion) each instance?

jsonchiu
02-22-2007, 04:35 AM
Well, first, you need to check the "export for actionscript" box in the properties of that symbol in the library, and give it an identifier - Ball_mc
Then, copy this code:
this.createEmptyMovieClip("holderClip", this.getNextHighestDepth();
for (var i:Number = 1; i <= 10; i++)
{
holderClip.attachMovie("Ball_mc", "Ball_mc" + i, holderClip.getNextHighestDepth(),
{_x:random(550), _y:random(400)});
}
Now test the movie. You should have 10 instances of Ball_mc that have the instance name of Ball_mc1, Ball_mc2, Ball_mc3...etc, and they are scattered around the stage.

Explanation:
this.createEmptyMovieClip("holderClip", this.getNextHighestDepth();
Create an empty movie clip to hold things. We don't want to use _root, and later on, if you want to delete all balls together, you can just use holderClip.removeMovieClip() instead of writing a loop.

for (var i:Number = 1; i <= 10; i++)
make a loop that loops through 1 to 10

holderClip.attachMovie("Ball_mc", "Ball_mc" + i, holderClip.getNextHighestDepth(),
{_x:random(550), _y:random(400)});
the attachMovie method is used to attach instances of a symbol from the library. the first parameter is the identifier which you entered earlier in the library. The second parameter is the instance name. Here I use "Ball_mc" + i, and that means the name will be Ball_mc1, Ball_mc2, .... Then, the getNextHighestDepths is used to give a unique depth, or level, to that movieclip. Remember, two movieclips cannot have the same depths, or else one will be destroyed. The last parameter is where the x y positions will be.

max1x106
02-22-2007, 03:00 PM
That worked quite nicely. Thank you.

max1x106
02-22-2007, 03:54 PM
Now that I can get instances on the layer at run time I am now challenged by how program them. For example, when I was using design time programming I had an instance where I could access an event to trigger a hittest. But now the layer itself is the only available level for programming because the instances don't as yet exist.

How do I program the onclipevent for these runtime created instances?