Groups | Blog | Home
all groups > flash actionscript > august 2006 >

flash actionscript : AS3 - dynamic class names with *new* operator


Ignitrix
8/4/2006 7:47:19 PM
I'm using AcrtionScript 3 and Adobe Flash 9 Public Alpha.

I have 50 movie clips in the Library that use Linkage to set the Class name
to: Img1, Img2, Img3, ..., Img50.
I have a parent class named RandImg. I want the constructor for RandImg to
randomly select one of the 50 movie clips from the Library and display it. I
could get this working by generating a random number, and then writing a really
huge switch statement to associate each possible random number with its
respective Library Movie Clip Class name, but I would much rather do this with
a dynamic/variable class name based on the random number, such as:

var nImgChoice:Number = Math.floor( Math.random( ) * 50 ) + 1;
var mcImg:MovieClip = new [ "Img"+String(nImgChoice) ] ( );
addChild( mcImg );

Note that this used to be possible in AS 2 by doing the following:

this.attachMovie( "Img"+String(nImgChoice) , "mcImg",
this.getNextHighestDepth());

Suggestions?
Thanks,
~JC
Raymond Basque
8/5/2006 12:00:00 AM
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.utils.getDefinitionByName;

var nImgChoice:Number = Math.floor( Math.random( ) * 50 ) + 1;
var ClassReference:Class = getDefinitionByName("Img"+String(nImgChoice) ) as
Class;
var instance:Object = new ClassReference();
addChild(DisplayObject(instance));

Ignitrix
8/7/2006 5:19:31 PM
Thanks Raymond! This worked beautifully! Thanks so much for your help!

I found some further information about getDefinitionByName at: http://www.kirupa.com/forum/showthre...64#post1902564
AddThis Social Bookmark Button