Friday, October 21, 2011

Quick Tip: Understanding getDefinitionByName()

In this Quick Tip, you’ll learn how to construct a reference to a class from a String, and then create an instance of that class, using a built-in AS3 function called getDefinitionByName(). You’ll also learn the best methods for using this in different situations.


Why Is getDefinitionByName() Useful?

getDefinitionByName() is very useful if you need to make new instances of classes by using a String. For example, if you had seven different tiles – each represented by a class called Tile1, Tile2, etc – and you needed to create an instance of each, you would have to write the following code:

private function createTiles():void
{
 var tile1:Tile1 = new Tile1();
 var tile2:Tile2 = new Tile2();
 var tile3:Tile3 = new Tile3();
 var tile4:Tile4 = new Tile4();
 var tile5:Tile5 = new Tile5();
 var tile6:Tile6 = new Tile6();
 var tile7:Tile7 = new Tile7();
 stage.addChild( tile1 );
 stage.addChild( tile2 );
 stage.addChild( tile3 );
 // You get the idea, it is very lengthy!
}

getDefinitionByName() allows you to solve this problem!


How to Use It

Now, the above code was a little messy and we had to type many lines just to make a few different tiles. This is how we could achieve the same goal using getDefinitionByName():

private function createTiles():void
{
 for( var i:int = 1; i < 8; i++ )
 {

  var tileRef:Class = getDefinitionByName( "Tile" + i ) as Class;
  var tile:tileRef = new tileRef();
  stage.addChild( tile );

 }
}

In line 6, getDefinitionByName() returns a reference of the class called “Tile + the current value of i in the for-loop“. So, when i is equal to 1, getDefinitionByName("Tile" + i); returns a reference to the class Tile1. We then create the tile and add it to the stage.

However, when you run this code, it will not work! You’ll get a variable is undefined error message, in most cases, because “Tile1″ might not be enough information for Flash to find the class. Let’s look at some workarounds.


Make It Work

There are a few commonly-used methods to solve the problem of the variable is undefined error you’ll get when you run the above code, and I am going to teach you what they are. I would also like to give credit to Gert-Jan van der Well of Floorplanner Tech Blog for this blog post.

Here are some of the methods you can use [...]

Quick Tip: Understanding getDefinitionByName()

No comments:

Post a Comment