Monday, 26 October 2009

Instantiate from library by class name

This maybe is one of the best hints for any as3 developer.

You have several objects in the Library, and some of them have sequenciall names, like "obj1", "obj2", "obj3"... and so on.

Normally if you want to instanciate an object from the library you would do like this:

var obj1:obj1=new obj1();
var obj2:obj2=new obj2();
...

What do you think... tedious, right? and not eficient, at all.

One of the solutions is to use the flash.util class that as a method called getDefinitionByName, wich can help a lot on this sort of thing.

By the upper example you just need a FOR cycle to instantiate all the objects. Imagine that I have from obj1 to obj5, this is how I would do it:

import flash.util.*;

private function instObj():void{
  for(var i:Number=1; i<6; i++){
    var name:String="obj"+i;
    var object = new (getDefinitionByName(name) as Class)();
    addChild(object);
  }
}