Portfolio / Blog / Dynamically Instantiate Classes In Flash AS3

Dynamically Instantiate Classes In Flash AS3

Use a loop to insert named items from your Library

Sometimes in Flash you need to cycle through a bunch of items that you have in your library and apply similar or identical code to each version, this is OK for 2 or 3 instances but many more an it becomes tiresome.

Using getDefinitionByName you can grab the item from your library and instantiate it as a class.

Bear in mind you'll need to make sure the item is available for export to ActionScript (right click on the item in the library, choose properties and tick 'export for ActionScript').

Obviously incremental names are the key here so your items would need to be named 'item_1',item_2' etc in the library. The prefix doesn't matter, so long as the numbers count up.

import flash.utils.getDefinitionByName;

var items= 2;
var instances:Array = new Array();

for(var i = 1; i <= items; i++){
   var dynClass:Class = getDefinitionByName("item_"+i) as Class;
   instances[i] = new dynClass();
  addChild(instances[i]);
   // Work with the instance e.g.
   instances[i].x = (i*100);
   instances[i].y = (i*100);

}

© 2012 Contact Matt | Built with Codeigniter