Understanding AS3 getDefinitionByName (for all eval maniacs)

Talking about Actionscript 3 and Flash.

Sometimes you may want to create a new class or DisplayObject only starting from its name. This is where something like an eval function would come into play, but we have to manage it in a different way with AS3.

Look at this movie:

Circles are four different objects called symbol1, symbol2, symbol3 and symbol4 and this is the script:

package {
	import flash.display.Sprite;
	public class Main extends Sprite {
		public function Main() {
			var s1:symbol1=new symbol1();
			addChild(s1);
			s1.x=95;
			s1.y=100;
			var s2:symbol2=new symbol2();
			addChild(s2);
			s2.x=245;
			s2.y=100;
			var s3:symbol3=new symbol3();
			addChild(s3);
			s3.x=395;
			s3.y=100;
			var s4:symbol4=new symbol4();
			addChild(s4);
			s4.x=545;
			s4.y=100;
		}
	}
}

Obviously it’s a bit unoptimized, just think about if we had a thousand objects. That’s when getDefinitionByName comes into play. It returns a reference to the class object of the class specified by the name parameter.

This means the same script can be written this way:

package {
	import flash.display.Sprite;
	import flash.utils.*
	public class Main extends Sprite {
		public function Main() {
			var symbolName:String;
			var symbolClass:Class;
			var s:Sprite;
			for (var i:int=1; i<=4; i++) {
				symbolName="symbol"+i;
				symbolClass=getDefinitionByName(symbolName) as Class;
				s=new symbolClass();
				addChild(s);
				s.x=95+150*(i-1);
				s.y=100;
			}
		}
	}
}

DisplayObjects names are passed as strings in getDefinitionByName method and created as generic classes that can be used anywhere in the movie.

If you want to see a real world example, cracks textures in my upcoming game have been made this way:

Starting from a random number I create the texture according to such number and the material name.

Something to keep in mind if you can't use anything similar to eval.

Download the source code.