7.19. Adding Movie Clips from the Library with ActionScript

Problem

You want to add a movie clip to your movie from the library without having to create an instance manually at authoring time.

Solution

Use the attachMovie( ) method.

Discussion

You should make a practice of using the attachMovie( ) method to add movie clips to your movies for any instances that are controlled entirely by ActionScript. The attachMovie( ) method allows you to add a movie clip using ActionScript at runtime instead of having to add the movie clip manually at authoring time. This is advantageous for several reasons, including:

  • With attachMovie( ), you can add movie clips dynamically. This is extremely important for any movies in which you need to load movie clips based on user information or data drawn from an XML file or a database.

  • It is bad practice to add movie clips to the Stage at authoring time that will be controlled exclusively by ActionScript. Don’t add movie clips to your Stage at authoring time unless they are being manually animated or you need to visually lay them out.

To use attachMovie( ), you must export the movie clip Library symbols. Library symbols are automatically exported with the movie when you create instances of them at authoring time. However, if a symbol is not explicitly used within the movie as a manually created instance, it is not automatically included in the .swf file (this saves space by not including unused symbols). In these cases, you need to tell Flash to export the symbol ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.