In many of our tutorials, we store assets in Flash's Library, link them to AS3, and then instantiate them at runtime. We do it with MovieClips created at authoring time, and with images imported to the Library at authoring time. Below we explain how to link a Flash Library asset to AS3 and instantiate the asset at runtime.
- Download all the files related to the above example: as3link.zip
In the simple Flash movie above, we imported a 160 by 160 jpeg image of the shuttle, shuttle160m.jpg, to the Library and linked it to AS3 under the name of 'Shuttle'. We also created a MovieClip on the Stage, then deleted it from the Stage. The MovieClip, named TestClip, remained in the Library.
Importing images to the Library looks the same in Flash CS3 and Flash CS4:
To link the image to AS3, select the image in the Library. Then go to the tiny menu in the upper right corner of the Library window:
Menu that opens looks a bit different in Flash CS3 and in Flash CS4. In Flash CS3, click on Linkage menu item:
In the window that opens, select Export for ActionScript. In the Class field type the name of the class associated with your asset. We chose 'Shuttle' as shuttle160m.jpg does not sound great as a class name. Note that the base class for the class associated with our exported image is the BitmapData class and not the Bitmap class.
Click OK. The window appears saying that since a class 'Shuttle' was not found, Flash will automatically generate such a class. Click OK. And you are all set.
In Flash CS4, in the Library menu click on Properties item:
If, in the window that opens, you see a tab Advanced, click on it to open the full view:
In the window that opens, select Export for ActionScript. In the Class field type the name of the class associated with your asset. We chose 'Shuttle' as before. Note that the base class for the class associated with your exported image is again the BitmapData class and not the Bitmap class.
If you are linking a MovieClip, the base class is the MovieClip class.
Creating Instances at Runtime
Here is the code for runtime instantiation.
'Shuttle' is a subclass of the BitmapData class. When instantiating the BitmaData class, we have to pass the width and the height to the constructor. In our case, they are 160 and 160. We instantiate 'Shuttle' and store the instance in the variable 'imgBD'. Then we create a Bitmap, 'shuttleImg' using 'imgBD' BitmapData.
var imgBD:BitmapData=new Shuttle(160,160);
var shuttleImg:Bitmap=new Bitmap(imgBD);
Now we create an instance of TestClip and store it the variable 'clip'.
var clip:MovieClip=new TestClip();
Note that having an asset linked to AS3, we can create as many different instances at runtime as we wish. We could create several instances of TestClip.