Game Development Reference
In-Depth Information
getDefinitionByName and Casting
Suppose you needed to instantiate a series of symbols or
classes that followed a numeric sequence, say for the purposes
of our example
It would be
very tedious to have to instantiate them one at a time and create a
lot of extra codes. It would probably look something like the
following:
square1
through
square10.
var square:Square = new square1();
addChild(square);
square = new square2();
addChild(square);
...
square = new square10();
addChild(square);
a class by its name.
In the flash.utils package, there is a method called getDefinition-
ByName , which accepts said name as a string parameter.
Luckily, Flash gives us the ability to
look up
for (var i:int = 1; i
= 10; i++) {
var squareClass:Class = getDefinitionByName(
<
"
square
"
+i)
as Class;
var square:Square = new squareClass();
addChild(square);
}
It returns a generic object that is a reference to the class, if it
exists. That object can then be converted to a class through an
operation known as casting . Casting is the process of telling
ActionScript to treat one object like a different kind of object. It is
most often used to treat a subclass like its superclass, which is
known as
casting because all of the functionality will be
guaranteed to carry over from the superclass. An example of this
would be with Sprite and MovieClip. MovieClip extends Sprite, so
it is safe to cast a MovieClip as a Sprite because their public
methods and variables will match. If we were to do the opposite,
castaSpriteasaMovieClip,itwouldbeconsideredan
safe
castingbecauseaSpritedoesnotcontainallofthemethodsand
variables of a MovieClip. While Flash will let you cast either
direction, it
unsafe
s generally a good idea to avoid casting to a subclass
unless you know for certain that the methods and variables you
want to call will be available. In the case of the above example,
converting a base object to a class is technically an unsafe cast-
ing, but the Class class (a confusing nomenclature to be sure)
contains no additional public methods or variables, so there is no
danger of causing an error. We
'
ll use casting and getDefinitionBy-
Name regularly later in game examples.
'
Search Nedrilad ::




Custom Search