Adding Dynamically Named Library Items to the Display List

June 27, 2009

To add a library item to a display object using as3, here is the basic method:

var dynamicClass:Class = getDefinitionByName("libraryName") as Class;
var mcFromLibrary:MovieClip = new dynamicClass();
addChild(mcFromLibrary);

dynamicClass is a variable typed as a Class returns a reference to the class object of the class specified by the name parameter.

“libraryName” is the the name given to the MovieClip’s Class in the Symbol Properties options in the flash library.

Don’t forget to import get the definitionByName class using

import flash.utils.getDefinitionByName;

This is especially useful when looping through an array to attach multiple instances of the same movieclip. Most recently I used it to pass the reference of a loader in the library since I wanted to use the same class to potentially attach different loaders depending on what was being loaded where and when in the program.