Instantiating an Object
Description: Robots are generated and deleted at the click of the mouse.
Author: John Bezanis
Added: March 1st 2007
Version: Flash 8
This tutorial demonstrates how you can create multiple instances of an object using actionscript. Begin by drawing your object. I drew (badly) a robot character.

Next select the object and right click it. Select Convert To Symbol. Set the name to robot, the type to Movie Clip and select Export for ActionScript. This will convert your drawing into a symbol. You will see it appear in the library. Since it is now a symbol, click it on the stage (not the library) and hit delete on the keyboard.
We are now going to create a button that creates robots, or instances of the robot symbol to be more technical. Select Window -> Common Libraries -> Buttons. Open the classic buttons folder, then Arcade buttons subfolder, then click and drag "arcade button - red" to the stage. You now have a button on the stage that doesn't do anything. Single click the button and open up the Actions tab. Insert the following code:
- on(press){
- createRobot();
- }
- var robotSerialNumber=1;
- function createRobot(){
- //create a robot at a random location on the stage and increment the robot serial number
- this.attachMovie("robot", ("r"+robotSerialNumber++), this.getNextHighestDepth(), {_x:Stage.width*Math.random(), _y:Stage.height*Math.random()});
- }
- function onPress(){
- this.removeMovieClip();
- }
The source file is available below for download.
Download Source File
Comments
what if you wanted to stop after a certain number of instances?
March 21st 2007 12:03AM - mr. P
Change the code on the button to check the serial number of the robot
on(press){
if(robotSerialNumber<=5){
createRobot();
}
}
This limits it to 5 robots total.
If you want to have a limit on the stage at one time, you could have a counter of the robots on stage, and increment it each time a robot is created and decremented each time a robot is destroyed.
on(press){
if(robotSerialNumber<=5){
createRobot();
}
}
This limits it to 5 robots total.
If you want to have a limit on the stage at one time, you could have a counter of the robots on stage, and increment it each time a robot is created and decremented each time a robot is destroyed.
March 21st 2007 06:03AM - John
How would you go about removing all the dynamically created instances with the click of one button? Even if there are several instances of a vriety of symbols.
April 19th 2007 07:04PM - lake
How can i rotate an image in same path and not blur in flash with the help of actionscript?
June 26th 2008 04:06AM - jefry
Add a Comment





