Denoteone
Denoteone

Reputation: 4055

How do I create a instance of a class using a variable?

I am trying to pass a variable to a method in one of my Classes so I can use it to create the correct movieClip (image)

My Class code looks like this:

package  {
    import flash.display.MovieClip;
    import flash.display.Sprite;


    public class SlideShow extends MovieClip{

        public function SlideShow() 
            {

                             //does something on start

        }

          //This function should take the string and use it as the class name below.
          public function addImages(BackGround:String):void
             {
            trace(BackGround);

            var main_bg:BackGround = new BackGround();
            addChild(main_bg);
                 }
         }
    }

and when I call the method from my maintimeline it looks like this:

var shoeSlide:SlideShow = new SlideShow(); 
shoeSlide.addImages("menPant"); 

SO "menPant" is acually the name I assigned to a class of a movieclip that has some images in it.

I am getting the following error:

SlideShow.as, Line 30   1046: Type was not found or was not a compile-time constant: BackGround.

Upvotes: 0

Views: 85

Answers (1)

xxneon
xxneon

Reputation: 61

make sure you import getDefinitionByName at the top of your class code if flash doesn't do it for you automatically. This should work.

public function addImages(BackGround:String):void
{
    var symbol_class:Class = getDefinitionByName(BackGround);
    //EDIT: removed data type :BackGround -- this will give an error.
    var main_bg = new symbol_class();
    addChild(main_bg);
}

Upvotes: 2

Related Questions