Adding movie clips with for loop action script 3

Hey wondering if anybody can help me, i am trying to add a load of move clips and make them clickable to the stage in action script 3,i can work out the spacing of them later i just keep getting errors while trying to add them using this :

for(var x:int = 1; x <= 10; x++)
        {

            var this["cardPrint"+x] :MovieClip = new this["card_"+x]();
            this.addChild(this["cardPrint"+x]);
            this["cardPrint"+x].addEventListener(MouseEvent.CLICK, this["click_"+x]);

        }

a point in the right direction would help alot thank you

Answers


this is a scope indicator that indicates the current class. So this["cardPrint"+x] is actually trying to find a variable with that name, but you can't declare a variable that is already a reference.

The only way to do what you want is like this:

public dynamic class Foobar 
{
    public function Foobar() 
    {
        for(var x:int = 1; x <= 10; x++)
        {
            this["cardPrint"+x] = new this["card_"+x]();
            this.addChild(this["cardPrint"+x]);
            this["cardPrint"+x].addEventListener(MouseEvent.CLICK, this["click_"+x]);
        }
    }
}

The key is making the class dynamic. That allows you to create variable names at run time and to create them in string form using the scope["varName"] syntax. If you are doing this on the timeline in Flash Pro, as I get the feeling you are, this is simply not possible the way you want to do it. You would be better off creating objects in the loop and storing them in an array to access them that way instead of using the syntax described above.

The datatype of each object created will be the same as whatever is instantiated, so you won't be able to set it to be MovieClip or similar.

"card_"+x also needs to be an instantiable object (a Class). If it is not, you cannot instantiate it and it will always error out.

I do want to caution you that is a very poor way of putting this together. The room for error is incredibly large and using this syntax will be difficult to do and difficult to read in your code.


Need Your Help

Capturing RaisePropertyChanged from MVVM Light?

c# .net windows-phone-7 mvvm mvvm-light

I currently have a Model with a boolean property that stores a checkbox value. When this value changes(checked/unchecked) I want to show or hide a textbox.

Error when decoding base64 with buffer. First argument needs to be a number

javascript node.js buffer

I am working on running different encoding statements based on the URL.