Saturday, January 30, 2010

AS3: Using a String to access Object / Class properties and getDefinitionByName

Consider for example you have a wonderful asset library and have a great scheme of describing maps and such in XML. So you get a asset name from XML and now want to add it to stage.

Remember you can access a Object property like so:

import my_assets.graphics;

var grap:graphics = new graphics();

var my_prop:String = "wonderful_img_class"; /* Got from XML :p */

stage.addChild(new graph[my_prop]); /* Now you asset is displayed */

wonderful_img_class in this case could refer to a image you have included using the [Embed(source=)] tag.

I initially spent time trying to use getDefinitionByName and got hit by the "Error #1065: Variable is not defined" before realising I could just do the above.

From my initial googling getDefinitionByName seems pretty unflexible and hence useless.

However if you want to investigate getDefinitionByName this post seems most useful:

http://www.rozengain.com/blog/2009/08/21/getdefinitionbyname-referenceerror-and-the-frame-metadata-tag/