Newest Articles

Flash Media Player
XML Driven Pie Chart
Base Defender
Hangman Game
8 Ball Pool

Popular Articles

Catapult Game
True Fullscreen Flash Mode
Mp3 Player with XML Playlist
FLV Player
Infinitely Zooming Image

Random Articles

Storing Data Similar to Cookies
Paddle Ball
Photo Reel
Motion along a Path
Mouse Following Preloader


Shapes the Game
Link to SwfSpot
Swf Spot

Contact me on Google+

rss feed

Instantiating an Object

Instantiating an Object
AddThis Social Bookmark Button
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.
convert to symbol
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:
  1. on(press){
  2.   createRobot();
  3. }
This inserts the code into the button instance. If you look at the code, you will see a call to the function createRobot(). Click the stage area to change the focus to the stage. You will notice the code in the Actions frame disappears because now the stage is focused, not the button. We are now going to write the createRobot() function. Insert the following code into the Actions Frame:
  1. var robotSerialNumber=1;
  2. function createRobot(){
  3.   //create a robot at a random location on the stage and increment the robot serial number
  4.   this.attachMovie("robot", ("r"+robotSerialNumber++), this.getNextHighestDepth(), {_x:Stage.width*Math.random(), _y:Stage.height*Math.random()});
  5. }
We can now create a robot with the click of the red button. Now, we are going to have each robot instance deleted when they are clicked. In the library, right-click -> edit the robot symbol. Open the Action Frame and insert the following code:
  1. function onPress(){
  2.   this.removeMovieClip();
  3. }
That's it. Robots are now created by clicking the red button and deleted by clicking a robot.

The source file is available below for download.
Download Source File
Comments Currently Disabled