Tuesday, November 6, 2007

adding a symbol dynamically from the library

how to add a symbol from the library?
in AS2,
this.attachMovie("square", "square", 1);

and in AS3,
var square1:square=new square();

but how do you add a symbol dynamically from the library? say if you have a shape stored in a variable:

var shape:String = "square";

and you want to add the symbol in the library with this name.
in AS2, simple! you could have written:
this.attachMovie(shape, shape, 1);

however the AS3 syntax doesn't obviously allow for dynamic references. so how is it done? (credit to kglad for assisting in this discovery)

getDefinitionByName is what you need to extract the class from the library like so:

import flash.utils.getDefinitionByName;

var classRef:Class = getDefinitionByName(shape) as Class;

var square1:* = new classRef();

2 comments:

AlpineButterfly said...

OK you made my day :-)

I've been trying to puzzle this one out for a while. I was trying to import a .wav file... only I had to add one more line for it to work...
I have no idea why!!

var sfx:String="button.wav";

var classRef:Class = getDefinitionByName(sfx) as Class;

var my_click_sd:Sound = new classRef();

click_sd = my_click_sd;

If I didn't add the last line, and tried to assign it directly,
(click_sd = new classRef();)
I got a TypeError: Error #1009. Any idea why???

In my variable list to start,
I'm starting with:
private var click_sd:Sound;

Craig Grummitt said...

sorry i've taken so long to respond. i've now set up my blog to notify me of comments! the solution to your problem is not immediately forthcoming to me, have you sorted it out?